客户端代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
int main(int argc, const char * argv[])
{
//创建套接字
int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
if (-1 == fd)
{
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 (-1 == ret)
{
perror("bind error");
exit(1);
}
//初始服务器的套接字信息
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;
}
服务器端代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
int main(int argc, const char * argv[])
{
//创建监听套接字
int lfd = socket(AF_LOCAL, SOCK_STREAM, 0);
if (-1 == lfd)
{
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 (-1 == ret)
{
perror("bind error");
exit(1);
}
//开始监听
ret = listen(lfd, 36);//设定同时监听的最大链接数量是36, linux最大值是128
if (-1 == ret)
{
perror("listen error");
exit(1);
}
//定义一个套接字,接收客户端信息
struct sockaddr_un client;
int length = sizeof(client);
int cfd = accept(lfd, (struct sockaddr*)&client, &length);
if (-1 == cfd)
{
perror("bind error");
exit(1);
}
//打印客户端绑定的socket文件地址
printf("client bind file:%s \n", client.sun_path);
//通信
while (1)
{
char buf[1024] = {0};
int len = recv(cfd,buf,sizeof(buf),0);
if(-1 == len) {perror("recv error"); exit(1);}
else if(0 == len) {printf("client close connect....\n");close(cfd);break;}
else {printf("recv buf: %s\n", buf); send(cfd, buf,strlen(buf)+1,0);}
}
close(cfd);
close(lfd);
return 0;
}