您现在的位置是:首页 >学无止境 >搭建简易TCP服务端,客户端网站首页学无止境
搭建简易TCP服务端,客户端
服务端
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define IP "192.168.109.129"
#define ERR_MSG(msg)do{
fprintf(stderr,"line: %d ",__LINE__);
perror(msg);
}while(0);
int main (int argc, const char *argv[])
{
//创建套接字
int sfd;
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;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(4652);//端口号是short类型16bit
sin.sin_addr.s_addr =inet_addr(IP);
//struct in_addr
//绑定
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
//监听
if(listen(sfd,128)<0)
{
ERR_MSG("listen");
return -1;
}
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
int newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s : %d] newfd : %d__%d ",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
char buf[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf,sizeof(buf));
res = recv(newfd,buf,sizeof(buf),0);//recv最后一个参数flags填0时,函数等价于read
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
printf("[%s : %d]newfd = %d 客户端下线__%d__ ",
inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
break;
}
printf("[%s : %d] %s__%d ",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf,__LINE__);
strcat(buf,"*_*");
res = send(newfd,buf,sizeof(buf),0);
if(res < 0)
{
ERR_MSG("send");
return -1;
}
printf("发送成功");
}
close(sfd);
close(newfd);
return 0;
}
客户端:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>#define IP "192.168.109.129"
#define ERR_MSG(msg) do{
fprintf(stderr,"line:%d ",__LINE__);
perror(msg);
}while(0)
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_port = htons(4652);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(IP);
socklen_t addrlen = sizeof(sin);
if(connect(cfd,(struct sockaddr*)&sin,addrlen) < 0)
{
ERR_MSG("connect");
return -1;
}printf("connect success:%d ",__LINE__);
char buf[128] = "";
ssize_t res = 0;
while(1)
{
printf("请输入>>>");
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(0 == res)
{
printf("服务器下线了 ");
break;
}
printf("%s__%d ",buf,__LINE__);}
close(cfd);return 0;
}