DAY1 网络编程(TCP客户端服务器)
作业:
TCP客户端服务器。
server服务器代码:
#include <myhead.h>
#define IP "192.168.110.52"
#define PORT 8886
#define BACKLOG 20
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);//IPV4通信 TCP通信协议
if(oldfd==-1)
{
perror("socket");
return -1;
}
//2.绑定IP和端口号
struct sockaddr_in server=
{
.sin_family=AF_INET,//IPV4
.sin_port=htons(PORT),//端口号转为网络字节序
.sin_addr.s_addr=inet_addr(IP),//IP
};
if(bind(oldfd,(struct sockaddr *)&server,sizeof(server))==-1)
{
perror("bind");
return -1;
}
//3.监听
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
//4.接收客户端连接请求创建新的描述符用于通讯
struct sockaddr_in client;//接收客户端信息的结构体
socklen_t client_len=sizeof(client);//计算出结构体大小
int newfd;
newfd =accept(oldfd,(struct sockaddr*)&client,&client_len);
if(newfd==-1)
{
perror("accept");
return -1;
}
printf("%s发来连接请求\n",inet_ntoa(client.sin_addr));
//5.循环收发信息
char buff[1024];
while(1)
{
memset(buff,0,sizeof(buff));
int len=recv(newfd,buff,sizeof(buff),0);//0:非阻塞 MSG_DONTWAIT
if(len==0)
{
printf("客户端断开连接\n");
break;
}
printf("%s\n",buff);
strcat(buff,"520");
send(newfd,buff,sizeof(buff),0);
}
close(oldfd);
close(newfd);
return 0;
}
client客户端代码:
#include <myhead.h>
#define IP "192.168.110.52"
#define PORT 8886
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
struct sockaddr_in server=
{
.sin_family=AF_INET,
.sin_port=htons(PORT),
.sin_addr.s_addr=inet_addr(IP),
};
if(connect(oldfd,(struct sockaddr *)&server,sizeof(server))==-1)
{
perror("connect");
return -1;
}
char buff[1024];
while(1)
{
fgets(buff,sizeof(buff),stdin);
buff[strlen(buff)-1]='\0';
send(oldfd,buff,sizeof(buff),0);
int len=recv(oldfd,buff,sizeof(buff),0);
if(len==0)
{
printf("服务器意外退出\n");
break;
}
printf("接收服务器:%s\n",buff);
}
close(oldfd);
return 0;
}