1、1Internet domain中面向连接通信实现(SOCKET通信)1、实验一(TCP协议通信)服务器端实现#include #include #include #include #include #include #include #include #include void sig_handler(int signo)pid_t pid;int stat;pid=waitpid(-1,while(pid0)printf(“child process terminated (PID: %ld)n“,(long)getpid();pid=waitpid(-1,return;int main(
2、int argc,char *argv)socklen_t clt_addr_len;int listen_fd;int com_fd;int ret;int i;static char recv_buf1024;int len;int port;pid_t pid;struct sockaddr_in clt_addr;struct sockaddr_in srv_addr;if(argc!=2)printf(“Usage: %s portn“,argv0);return 1;port=atoi(argv1);if(signal(SIGCHLD,sig_handler)0)printf(“M
3、essage from client(%d): %sn“,len,recv_buf);if(recv_buf0=)break;for(i=0;i#include #include #include #include #include int main(int argc,char *argv)int connect_fd;int ret;char snd_buf1024;int i;int port;int len;static struct sockaddr_in srv_addr;if(argc!=3)printf(“Usage: %s server_ip_address portn“,ar
4、gv0);return 1;port=atoi(argv2);connect_fd=socket(PF_INET,SOCK_STREAM,0);if(connect_fd0)write(connect_fd,snd_buf,len);len=read(connect_fd,snd_buf,len);if(len0)printf(“Message from server: %sn“,snd_buf);if(snd_buf0=)break;close(connect_fd);4return 0;2、实验二#include #include #include #include #include #i
5、nclude #include #include #define MY_PORT 3333int main(int argc ,char *argv)int listen_fd,accept_fd;struct sockaddr_in client_addr;int n;if(listen_fd=socket(AF_INET,SOCK_STREAM,0)#include #include #include #include #include #include #include #include #define SERVER_PORT 8888 #define MAX_MSG_SIZE 1024
6、 void udps_respon(int sockfd) struct sockaddr_in addr; int addrlen,n; char msgMAX_MSG_SIZE; while(1) /* 从网络上读,并写到网络上 */ bzero(msg,sizeof(msg); / 初始化,清零addrlen = sizeof(struct sockaddr); n=recvfrom(sockfd,msg,MAX_MSG_SIZE,0,(struct sockaddr*) / 从客户端接收消息msgn=0; /* 显示服务端已经收到了信息 */ fprintf(stdout,“Serve
7、r have received %s“,msg); / 显示消息 int main(void) int sockfd; struct sockaddr_in addr; /* 服务器端开始建立 socket 描述符 */ sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd#include #include #include #include #include #include #include #include #include #define SERVER_PORT 8888 #define MAX_BUF_SIZE 1024 void udpc_r
8、equ(int sockfd,const struct sockaddr_in *addr,int len) char bufferMAX_BUF_SIZE; int n; while(1) /* 从键盘读入,写到服务端 */ printf(“Please input char:n“);fgets(buffer,MAX_BUF_SIZE,stdin); sendto(sockfd,buffer,strlen(buffer),0,addr,len); bzero(buffer,MAX_BUF_SIZE); int main(int argc,char *argv) int sockfd; str
9、uct sockaddr_in addr; if(argc!=2) fprintf(stderr,“Usage:%s server_ipn“,argv0); exit(1); /* 建立 sockfd 描述符 */ sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd0) fprintf(stderr,“Socket Error:%sn“,strerror(errno); exit(1); /* 填充服务端的资料 */ bzero( addr.sin_family=AF_INET; addr.sin_port=htons(SERVER_PORT);if(inet_aton(argv1, exit(1); 7 udpc_requ(sockfd, / 进行读写操作close(sockfd);