Webserver(4.9)本地套接字的通信
目录
- 本地套接字
本地套接字
TCP\UDP实现不同主机、网络通信
本地套接字实现本地的进程间的通信,类似的,一般采用TCP的通信流程
生成套接字文件
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/un.h>int main(){unlink("client.sock");//1.创建套接字int cfd=socket(AF_LOCAL,SOCK_STREAM,0);if(cfd==-1){perror("socket");exit(-1);}//2.绑定本地套接字文件struct sockaddr_un addr;addr.sun_family=AF_LOCAL;strcpy(addr.sun_path,"client.sock");int ret=bind(cfd,(struct sockaddr *)&addr,sizeof(addr));if(ret==-1){perror("bind");exit(-1);}//3.连接服务器struct sockaddr_un seraddr;seraddr.sun_family=AF_LOCAL;strcpy(seraddr.sun_path,"server.sock");ret=connect(cfd,(struct sockaddr *)&seraddr,sizeof(addr));if(ret==-1){perror("connect");exit(-1);}//4.通信int num=0;while(1){char buf[128];sprintf(buf,"hello,i am client:%d\n",num++);send(cfd,buf,strlen(buf)+1,0);printf("clientsay:%s\n",buf);//接收数据int len=recv(cfd,buf,sizeof(buf),0);if(len==-1){perror("recv");exit(-1);}else if(len==0){printf("server closed...\n");break;}else if(len>0){printf("server say:%s\n",buf);}sleep(1);}close(cfd);return 0;
}
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/un.h>int main(){unlink("server.sock");//1.创建套接字int lfd=socket(AF_LOCAL,SOCK_STREAM,0);if(lfd==-1){perror("socket");exit(-1);}//2.绑定本地套接字文件struct sockaddr_un addr;addr.sun_family=AF_LOCAL;strcpy(addr.sun_path,"server.sock");int ret=bind(lfd,(struct sockaddr *)&addr,sizeof(addr));if(ret==-1){perror("bind");exit(-1);}//3.监听ret=listen(lfd,100);if(ret==-1){perror("listen");exit(-1);}//4.等待客户端连接struct sockaddr_un cliaddr;int len=sizeof(cliaddr);int cfd=accept(lfd,(struct sockaddr *)&cliaddr,&len);if(cfd==-1){perror("accepr");exit(-1);}printf("client socket filename:%s\n",cliaddr.sun_path);//5.通信while(1){char buf[128];int len=recv(cfd,buf,sizeof(buf),0);if(len==-1){perror("recv");exit(-1);}else if(len==0){printf("client closed...\n");break;}else if(len>0){printf("client say:%s\n",buf);send(cfd,buf,len,0);}}close(cfd);close(lfd);return 0;
}