- 基于TCP的本地通信(服务器):
- 创建流程:
- 一、创建字节流式套接字(socket函数):
int sock_fd = socket(AF_LOCAL,SOCK_STREAM,0);
- 二、创建服务器和客户机的本地网络信息结构体并填充服务器本地网络信息结构体 (struct sockaddr_un):
- 本地网络信息结构体:
#include struct sockaddr_un {sa_family_t sun_family; charsun_path[108];};
struct sockaddr_un serveraddr,clientaddr;socklen_t serveraddr_len = sizeof(serveraddr);socklen_t clientaddr_len = sizeof(clientaddr);memset(&serveraddr,0,serveraddr_len);memset(&clientaddr,0,clientaddr_len);serveraddr.sun_family = AF_LOCAL;strcpy(serveraddr.sun_path,"./tcpserver");
bind(sock_fd,(struct sockaddr *)&serveraddr,serveraddr_len);
listen(sock_fd,5);
accept(sock_fd,(struct sockaddr *)&clientaddr,&clientaddr_len);
- 六、服务器端收发数据(recv函数、send函数):
memset(buf,0,sizeof(buf));if(-1 == (nbytes = recv(accept_fd,buf,sizeof(buf),0))){perror("recv error");exit(-1);}else if(0 == nbytes){printf("客户端[%s]断开了连接\n",clientaddr.sun_path);break;}printf("客户端[%s]发来数据[%s]\n",clientaddr.sun_path,buf);strcat(buf,"-------k");ret = send(accept_fd,buf,sizeof(buf),0);if(-1 == ret){perror("send error");exit(-1);}
close(accept_fd);close(sock_fd);
#include #include #include #include #include #include #include #include #include #include int main(int argc, char const *argv[]){int sock_fd = socket(AF_LOCAL,SOCK_STREAM,0);if(-1 == sock_fd){perror("socket error");exit(-1);}struct sockaddr_un serveraddr,clientaddr;socklen_t serveraddr_len = sizeof(serveraddr);socklen_t clientaddr_len = sizeof(clientaddr);memset(&serveraddr,0,serveraddr_len);memset(&clientaddr,0,clientaddr_len);serveraddr.sun_family = AF_LOCAL;strcpy(serveraddr.sun_path,"./tcpserver");if(-1 == bind(sock_fd,(struct sockaddr *)&serveraddr,serveraddr_len)){perror("bind error");exit(-1);}if(-1 == listen(sock_fd,5)){perror("listen error");exit(-1);}int accept_fd = 0;char buf[128] = {0};int nbytes = 0;int ret = 0;printf("本地通信之TCP服务器启动!!!\n");while(true){ accept_fd = accept(sock_fd,(struct sockaddr *)&clientaddr,&clientaddr_len);if(-1 == accept_fd){perror("accept error");exit(-1);}while(true){memset(buf,0,sizeof(buf));if(-1 == (nbytes = recv(accept_fd,buf,sizeof(buf),0))){perror("recv error");exit(-1);}else if(0 == nbytes){printf("客户端[%s]断开了连接\n",clientaddr.sun_path);break;}printf("客户端[%s]发来数据[%s]\n",clientaddr.sun_path,buf);strcat(buf,"-------k");ret = send(accept_fd,buf,sizeof(buf),0);if(-1 == ret){perror("send error");exit(-1);}}close(accept_fd);}close(sock_fd);return 0;}
本地通信之TCP服务器启动!!!客户端[./tcpclient]发来数据[hello]客户端[./tcpclient]发来数据[hi]客户端[./tcpclient]发来数据[I Love China!!!]
- 特别注意:
strcpy(serveraddr.sun_path,"./tcpserver");
中tcpserver文件
是套接字文件
;- 如下所示:
srwxrwxr-x 1 linux linux 0 11月 10 05:58 tcpserver