环境:Linux
语言:C/C++
通信方式:TCP
下面用TCP协议编写一个简单的服务器、客户端,其中服务器端一直监听本机的6666号端口。如果收到连接请求,将接收请求并接收客户端发来的消息;客户端与服务器端建立连接。连接建立成功后,读取文件内容(/root/workspace/socket-picture/bizhi.jpg),发送给服务器端,服务器端新建new1.jpg文件,将接收到的文件内容保存到new1.jpg中,new1.jpg在当前目录下;
Server.cpp
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<errno.h> 5 #include<sys/types.h> 6 #include<sys/socket.h> 7 #include<netinet/in.h> 8 #include<unistd.h> 9 10 #define MAXLINE 4096 11 12 int main(int argc, char** argv){ 13 int listenfd, connfd; 14 struct sockaddr_in servaddr; 15 char buff[4096]; 16 FILE *fp; 17 int n; 18 19 if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ 20 printf("create socket error: %s(errno: %d) ",strerror(errno),errno); 21 return 0; 22 } 23 printf("----init socket---- "); 24 25 memset(&servaddr, 0, sizeof(servaddr)); 26 servaddr.sin_family = AF_INET; 27 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 28 servaddr.sin_port = htons(6666); 29 //设置端口可重用 30 int contain; 31 setsockopt(listenfd,SOL_SOCKET, SO_REUSEADDR, &contain, sizeof(int)); 32 33 if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){ 34 printf("bind socket error: %s(errno: %d) ",strerror(errno),errno); 35 return 0; 36 } 37 printf("----bind sucess---- "); 38 39 if( listen(listenfd, 10) == -1){ 40 printf("listen socket error: %s(errno: %d) ",strerror(errno),errno); 41 return 0; 42 } 43 if((fp = fopen("new1.jpg","ab") ) == NULL ) 44 { 45 printf("File. "); 46 close(listenfd); 47 exit(1); 48 } 49 50 printf("======waiting for client's request====== "); 51 while(1){ 52 struct sockaddr_in client_addr; 53 socklen_t size=sizeof(client_addr); 54 if( (connfd = accept(listenfd, (struct sockaddr*)&client_addr, &size)) == -1){ 55 printf("accept socket error: %s(errno: %d)",strerror(errno),errno); 56 continue; 57 } 58 while(1){ 59 n = read(connfd, buff, MAXLINE); 60 if(n == 0) 61 break; 62 fwrite(buff, 1, n, fp); 63 } 64 buff[n] = '