簡單的,使用套接字進行TCP通訊(使用程序實現併發)。
阿新 • • 發佈:2019-02-02
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> #include <sys/socket.h> #define N 100 int main() { pid_t pid; int listenfd; int connectfd; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; socklen_t clilen; char msg[N]; int ret; int i; int n; int opt = 1; listenfd = socket(AF_INET,SOCK_STREAM,0); if(listenfd == -1) { printf("socket error!\n"); exit(-1); } setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(8000); ret = bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if(ret == -1) { printf("bind error!\n"); exit(-1); } ret = listen(listenfd,1024); if(ret == -1) { printf("listen error!\n"); exit(-1); } for(;;) { clilen = sizeof(cliaddr); connectfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen); if(connectfd == -1) { printf("accept error!\n"); exit(-1); } if((pid = fork()) == 0) { close(listenfd); while(1) { n = recvfrom(connectfd,msg,N,0,(struct sockaddr *)&cliaddr,&clilen); if(n == 0) { printf("client is closed!\n"); close(connectfd); exit(0); //break; } msg[n] = '\0'; printf("recv:%s\n",msg); for(i = 0;i < n; i++) { if(msg[i] >= 'a' && msg[i] <= 'z') { msg[i] -= 32; } } printf("send:%s\n",msg); sendto(connectfd,msg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr)); } // close(connectfd); } } close(listenfd); return 0; }
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <string.h> #define N 100 int main(int argc,char **argv) { int sockfd; struct sockaddr_in servaddr; char sendbuf[N]; char recvbuf[N]; int ret; int n; if(argc != 2) { printf("usage:server <ip address>\n"); exit(-1); } sockfd = socket(AF_INET,SOCK_STREAM,0); if(sockfd == -1) { printf("socket error!\n"); exit(-1); } bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(argv[1]); servaddr.sin_port = htons(8000); ret = connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if(ret == -1) { printf("connect error!\n"); exit(-1); } //printf("Please enter info:"); while(fgets(sendbuf,N,stdin) != 0) { sendto(sockfd,sendbuf,strlen(sendbuf),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); n = recvfrom(sockfd,recvbuf,N,0,NULL,NULL); recvbuf[n] = '\0'; printf("recv:%s",recvbuf); } close(sockfd); return 0; }