**TCP本地套接字通信:**为了实现没有血缘关系的进程之间通信,通常会采用本地套接字进行通信,在两个进程分别绑定好了套接字文件(.sock),运行程序后将产生两个套接字文件,这两个文件共享同一片内核缓冲区,内核将完成两个进程之间的数据传输
实现流程(TCP实现)
服务器
1.创建套接字
int lfd = socket(AF_LOCAL,SOCK_STREAM,0);
2.绑定
struct sockaddr_un serv;
serv.sun_family = af_local;
strcpy(serv.sun_path,“server.socket”);
bind(lfd,(struct sockaddr*)&serv,len);
3.设置监听
listen();
4.等待接收连接请求
struct sockaddr_un client;
int len = sizeof(client);
int cfd = accept(lfd,&client,&len);
5.通信
发送数据:send
接收数据:recv
6.断开连接
close(cfd);
close(lfd);
客户端
1.创建套接字
int fd =socket(af_local,sock_stream,0);
2.绑定套接字文件
struct sockaddr_un client;
client.sun_family = af_local;
strcpy(client.sun_path,“client.socket”);
bind(fd,(strcut sockaddr*)&client,len);
3.建立连接
struct sockaddr_un serv;
serv.sun_family = af_local;
strcpy(serv.sun_path,“server.soket”);
connetc(fd,&serv,sizeof(server));
4.通信
发送数据:send();
接收数据:recv();
5.关闭连接
close(fd);
完整代码
服务器
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, const char* argv[])
{
int lfd = socket(AF_LOCAL, SOCK_STREAM, 0);
if(lfd == -1)
{
perror("socket error");
exit(1);
}
// 如果套接字文件存在, 删除套接字文件
unlink("server.sock");
// 绑定
struct sockaddr_un serv;
serv.sun_family = AF_LOCAL;
strcpy(serv.sun_path, "server.sock");
int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret == -1)
{
perror("bind error");
exit(1);
}
// 监听
ret = listen(lfd, 36);
if(ret == -1)
{
perror("listen error");
exit(1);
}
// 等待接收连接请求
struct sockaddr_un client;
socklen_t len = sizeof(client);
int cfd = accept(lfd, (struct sockaddr*)&client, &len);
if(cfd == -1)
{
perror("accept error");
exit(1);
}
printf("======client bind file: %s\n", client.sun_path);
// 通信
while(1)
{
char buf[1024] = {0};
int recvlen = recv(cfd, buf, sizeof(buf), 0);
if(recvlen == -1)
{
perror("recv error");
exit(1);
}
else if(recvlen == 0)
{
printf("clietn disconnect ....\n");
close(cfd);
break;
}
else
{
printf("recv buf: %s\n", buf);
send(cfd, buf, recvlen, 0);
}
}
close(cfd);
close(lfd);
return 0;
}
客户端
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, const char* argv[])
{
int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
if(fd == -1)
{
perror("socket error");
exit(1);
}
unlink("client.sock");
// ================================
// 给客户端绑定一个套接字文件
struct sockaddr_un client;
client.sun_family = AF_LOCAL;
strcpy(client.sun_path, "client.sock");
int ret = bind(fd, (struct sockaddr*)&client, sizeof(client));
if(ret == -1)
{
perror("bind error");
exit(1);
}
// 初始化server信息
struct sockaddr_un serv;
serv.sun_family = AF_LOCAL;
strcpy(serv.sun_path, "server.sock");
// 连接服务器
connect(fd, (struct sockaddr*)&serv, sizeof(serv));
// 通信
while(1)
{
char buf[1024] = {0};
fgets(buf, sizeof(buf), stdin);
send(fd, buf, strlen(buf)+1, 0);
// 接收数据
recv(fd, buf, sizeof(buf), 0);
printf("recv buf: %s\n", buf);
}
close(fd);
return 0;
}