1,思维导图2,TCP通信
服务器端
#include<myhead.h>
#define JCHM 4514
#define IPDZ "192.168.0.113"
#define BACKLOG 5
int main(int argc,const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
printf("旧套接字创建成功\n");
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_port = htons(JCHM),
.sin_addr.s_addr= inet_addr(IPDZ)
};
int sum1=bind(oldfd,(struct sockaddr *)&sin,sizeof(sin));
if(sum1==-1)
{
perror("bind");
return -1;
}
printf("主机IP和端口号绑定成功\n");
int sum2=listen(oldfd,BACKLOG);
if(sum2==-1)
{
perror("listen");
return -1;
}
printf("监听客户端请求\n");
int newfd;
struct sockaddr_in cin;
socklen_t cinlen=sizeof(cin);
newfd = accept(oldfd,(struct sockaddr *)&cin,&cinlen);
if(newfd==-1)
{
perror("accept");
return -1;
}
printf("%s:%d客户端发来请求\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
char buff[1024]="";
while(1)
{
int len = recv(newfd,buff,sizeof(buff),0);
printf("客户端发来消息:%s\n",buff);
if(len==0)
{
printf("客户端已退出\n");
break;
}
memset(buff,0,sizeof(buff));
}
close(newfd);
close(oldfd);
return 0;
}
客户端
#include<myhead.h>
#define JCHM 4514
#define IPDZ "192.168.0.113"
int main(int argc,const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("oldfd");
return -1;
}
struct sockaddr_in cin = {
.sin_family = AF_INET,
.sin_port = htons(JCHM),
.sin_addr.s_addr = inet_addr(IPDZ)
};
int sum = connect(oldfd,(struct sockaddr *)&cin,sizeof(cin));
if(sum==-1)
{
perror("connect");
return -1;
}
printf("连接服务器成功\n");
char buff[1024]="";
while(1)
{
memset(buff,0,sizeof(buff));
fgets(buff,sizeof(buff),stdin);
send(oldfd,buff,sizeof(buff),0);
}
close(oldfd);
return 0;
}