流式域套接字服务器端实现(TCP)
#include <myhead.h>
#define BACKLOG 5
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_UNIX,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
if(access("./server",F_OK)==0)
{
if(unlink("./server")==-1)
{
perror("unlink");
return -1;
}
}
struct sockaddr_un ser;
ser.sun_family=AF_UNIX;
strcpy(ser.sun_path,"./server");
if(bind(oldfd,(struct sockaddr *)&ser,sizeof(ser))==-1)
{
perror("bind");
return -1;
}
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
int newfd=accept(oldfd,NULL,NULL);
if(newfd==-1)
{
perror("accept");
return -1;
}
char buff[1024];
while(1)
{
int len=recv(newfd,buff,sizeof(buff),0);
if(len==0)
{
printf("客户端跑了\n");
break;
}
strcat(buff,"/suc");
send(newfd,buff,sizeof(buff),0);
printf("转发成功\n");
}
return 0;
}
流式域套接字客户端实现(TCP)
#include <myhead.h>
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_UNIX,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
if(access("./clinet",F_OK)==0)
{
if(unlink("./clinet")==-1)
{
perror("unlink");
return -1;
}
}
struct sockaddr_un ser;
ser.sun_family=AF_UNIX;
strcpy(ser.sun_path,"./server");
if(connect(oldfd,(struct sockaddr *)&ser,sizeof(ser))==-1)//4、连接服务器
{
perror("connect");
return -1;
}
char buff[1024];
while(1)
{
printf("请输入要发送的信息:");
fgets(buff,sizeof(buff),stdin);
buff[strlen(buff)-1] = '\0';
send(oldfd,buff,sizeof(buff),0);//发送信息
printf("发送成功\n");
recv(oldfd,buff,sizeof(buff),0);//接收服务器信息
printf("接收服务器的信息:%s\n",buff);//输出接收到的信息
}
return 0;
}