TCP服务器客户端搭建
服务器:
#include
#include
#include
#include
#include
#include
#include
#include
#define ERR_MSG(msg)do{\
fprintf(stderr,"lind%d\n",__LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.31.226"
int main (int argc, const char *argv[])
{
// 创建套接字socket
int sfd=socket(AF_INET,SOCK_STREAM,0);
//判断
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
//允许端口快速被重复使用,当检测到该端口好没有被进程正常占用时候
//允许端口快速被新的进程占用覆盖
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
//将ip地址和端口号绑定到套接字文件中
//填充服务器
struct sockaddr_in sin;
sin.sin_family =AF_INET;
sin.sin_port=htons(5885);//端口号
sin.sin_addr.s_addr=inet_addr(IP);//ip
//绑定
if ( bind(sfd,(struct sockaddr *)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success__%d__\n",__LINE__);
//将套接字设置为被动监听状态
if(listen(sfd,128)>0)//backlog一般默认写128
{
ERR_MSG("listen");
return -1;
}
struct sockaddr_in cin;//存储连接成功的客户端信息
socklen_t addrlen=sizeof(cin);
//交换客户端,accept 阻塞
int newfd=accept(sfd,(struct sockaddr *)&cin,&addrlen);//新的文件描述符用来对接客户端
if(newfd<0)
{
ERR_MSG("accept");
return -1;
}
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(res==0)
{
printf("[%s :%d]newfd=%d客户端下线__%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);//把ip地址转成点分十进制
break;
}
printf("[%s :%d]newfd=%d :%s _%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf,__LINE__);
//发送信息到客户端
//fgets(buf,sizeof(buf),stdin);
strcat(buf,"*-*");
if(send(newfd,buf,sizeof(buf),0)<0)
{
ERR_MSG("send");
return -1;
}
printf("发送成功\n");
}
close(sfd);
close(newfd);
return 0;
}
客户端
#include
#include
#include
#include
#include
#include
#include
#include
#define ERR_MSG(msg)do{\
fprintf(stderr,"line%d\n",__LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.31.226"
int main (int argc, const char *argv[])
{
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd<0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port =htons(5885);
sin.sin_addr.s_addr=inet_addr(IP);
//连接到指定服务器
if(connect(cfd,(struct sockaddr *)&sin,sizeof(sin))<0)
{
ERR_MSG("connect");
return -1;
}
char buf[128]="";
ssize_t res=0;
while(1)
{
printf("请输入\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
//发送
if(send(cfd,buf,sizeof(buf),0)<0)
{
ERR_MSG ("send");
return -1;
}
//接收对端发的数据包
bzero(buf,sizeof(buf));
res=recv(cfd,buf,sizeof(buf),0);
if(res<0)
{
ERR_MSG ("recv");
return -1;
}else if(res==0)
{
printf("服务器下线\n");
break;
}
printf("%s__%d\n",buf,__LINE__);
}
close(cfd);
return 0;
}