用于:同一主机内通信 解决了管道的半双工机制,可以实现全双工,也是进程间通信的一种,和有名管道一样依赖文件路径进行通信
unix 域套接字分为流式套接字(SOCK_STREAM)和用户数据报套接字(SOCK_DGRAM)
流式套接字:socket---bind---listen---accept--read/write---close
用户数据套接字:socket--bind--recvfrom/sendto---close
server
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/un.h>
#define PATH "./file.text"
//文件不存在 他默认创建一个文件进行通信
void * handler(void * argc);
static int flag = 0;
void main()
{
int fd;
int bFlag;
pthread_t t1;
struct sockaddr_un server;
//1.socket
fd = socket(AF_UNIX,SOCK_STREAM,0);
if(fd < 0)
{
printf("socket error!\n");
exit(-1);
}
else
printf("socket succeed!\n");
if(access(PATH,F_OK) < 0)
{
printf("文件不存在\n");
}
else
unlink(PATH);
//2.bind
server.sun_family = AF_UNIX;
strcpy(server.sun_path,PATH);
bFlag = bind(fd,(struct sockaddr *)&server,sizeof(struct sockaddr_un));
if(bFlag < 0)
{
printf("bind error\n");
}
else
printf("bind succeed\n");
//3.listen
listen(fd,5);
//4.accept
int len = sizeof(struct sockaddr_un);
while(1)
{
int newFd = accept(fd,NULL,NULL);
if(newFd < 0)
{
printf("连接失败\n");
}
else
{
printf("连接成功\n");
flag++;
printf("客户端%d已接入\n",flag);
pthread_create(&t1,NULL,handler,(void *)&newFd);
pthread_join(t1,NULL);
}
}
}
void * handler(void * argc)
{
char rBuf[128]={'\0'};
char wBuf[128]={'\0'};
int ret;
while(1)
{
//5.read/write
memset(rBuf,'\0',sizeof(rBuf)+1);
memset(wBuf,'\0',sizeof(wBuf)+1);
ret = read(*(int *)argc,rBuf,sizeof(rBuf)+1);
if(ret > 0)
{
printf("来自客户端:%s\n",rBuf);
}
else if(ret < 0)
{
printf("没有读到数据\n");
}
if(!strncasecmp(rBuf,"quit",4))
{
break;
}
printf("请输入您要发送的信息:");
gets(wBuf);
write(*(int *)argc,wBuf,sizeof(wBuf)+1);
}
close(*(int *)argc);
printf("客户端%d已退出\n",flag);
pthread_exit(NULL);
}
client
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/un.h>
#define PATH "./file.text"
//文件不存在 他默认创建一个文件进行通信
void main()
{
int fd;
char wBuf[128];
char rBuf[128];
struct sockaddr_un server;
//1.socket
fd = socket(AF_UNIX,SOCK_STREAM,0);
if(fd < 0)
{
printf("socket error\n");
}else
printf("socket succeed!\n");
if(access(PATH,F_OK) < 0)
{
printf("文件不存在\n");
}else
printf("文件存在\n");
server.sun_family = AF_UNIX;
strcpy(server.sun_path,PATH);
//2.connect
connect(fd,(struct sockaddr *)&server,sizeof(struct sockaddr_un));
//3.read/write
while(1)
{
memset(wBuf,'\0',sizeof(wBuf)+1);
memset(rBuf,'\0',sizeof(rBuf)+1);
printf("请输入您要发送的信息:");
gets(wBuf);
write(fd,wBuf,sizeof(wBuf)+1);
read(fd,rBuf,sizeof(rBuf)+1);
if(!strncasecmp(wBuf,"quit",4))
{
break;
}
printf("来自服务端:%s\n",rBuf);
}
//4.close
close(fd);
printf("客户端已退出----\n");
}