tcp流式域套接字
客户端:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<sys/un.h>
#define ERR_MSG(msg)do{\
fprintf(stderr,"__%d__:",__LINE__);\
perror(msg);\
}while(0);
int main(int argc, const char *argv[])
{
//创建套接字
int sfd=socket(AF_UNIX,SOCK_STREAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path,"./unix");
//连接服务器的IP和端口
if(connect(sfd,(struct sockaddr*)&sun,sizeof(sun))<0)
{
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
char buf[128]="";
ssize_t res;
while(1)
{
bzero(buf,sizeof(buf));
printf("请输入>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
//send发送
if(send(sfd,buf,sizeof(buf),0)<0)
{
ERR_MSG("send");
return -1;
}
printf("send success\n");
//接收
bzero(buf,sizeof(buf));
res=recv(sfd,buf,sizeof(buf),0);
if(res<0)
{
ERR_MSG("recv");
return -1;
}
else if(0==res)
{
printf("服务器关闭\n");
break;
}
printf(":%s\n",buf);
}
//close关闭套接字
close(sfd);
return 0;
}
服务器:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<sys/un.h>
#define ERR_MSG(msg)do{\
fprintf(stderr,"__%d__:",__LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
//创建套接字
int sfd=socket(AF_UNIX,SOCK_STREAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
//判断要绑定的套接字文件路径是否存在
if(access("./unix",F_OK)==0)
{
//如果存在,将该套接字文件删除
if(unlink("./unix")<0)
{
ERR_MSG("unlink");
return -1;
}
}
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path,"./unix");
//绑定服务器的IP和端口
if(bind(sfd,(struct sockaddr*)&sun,sizeof(sun))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//listen监听
if(listen(sfd,10)<0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success\n");
struct sockaddr_un cun; //接收客户端的IP和端口
socklen_t addrlen = sizeof(cun);
//获取新的文件描述符,用于通信、交互
//accept
int newfd=accept(sfd,(struct sockaddr*)&cun,&addrlen);
if(newfd<0)
{
ERR_MSG("accept");
return -1;
}
printf("newfd=%d\n",newfd);
char buf[128]="";
ssize_t res=0;
while(1)
{
bzero(buf,sizeof(buf));
//接收
res=recv(newfd,buf,sizeof(buf),0);
if(res<0)
{
ERR_MSG("recv");
return -1;
}
else if(0==res)
{
fprintf(stderr,"newfd=%d客户端关闭\n",newfd);
break;
}
printf("newfd=%d: %s\n",newfd,buf);
//发送
strcat(buf,"*_*");
if(send(newfd,buf,sizeof(buf),0)<0)
{
ERR_MSG("send");
return -1;
}
printf("发送成功\n");
}
//close关闭套接字
close(newfd);
close(sfd);
return 0;
}