网络编程 day1.2~day2——TCP和UDP的通信基础(TCP)
笔记脑图
作业:
1、将虚拟机调整到桥接模式联网。
2、TCP客户端服务器实现一遍。
服务器
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
#define BACKLOG 20
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(bind(oldfd,(struct sockaddr *)&server,sizeof(server))==-1)
{
perror("bind");
return -1;
}
//监听
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
//接收通信
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));
//循环收发
char buff[1024];
while(1)
{
memset(buff,0,sizeof(buff));
//int len=read(newfd,buff,sizeof(buff));
int len=recv(newfd,buff,sizeof(buff),0);
if(len==0)
{
printf("客户端下线\n");
break;
}
printf("%s\n",buff);
strcat(buff,"5201314");
//write(newfd,buff,sizeof(buff));
send(newfd,buff,sizeof(buff),0);
}
//关闭
close(oldfd);
close(newfd);
return 0;
}
客户端
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
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;
}
原文地址:https://blog.csdn.net/2301_77576552/article/details/143894071
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!