1.tcp实现通信
服务器:
//tcp服务端
#include
#define SERPORT 8888
#define IP "192.168.125.6"
int main(int argc, const char *argv[])
{
//1.创建套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
//2.绑定
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(SERPORT);
ser.sin_addr.s_addr=inet_addr(IP);
bind(sfd,(struct sockaddr*)&ser,sizeof(ser));
printf("服务器已上线!\n");
//3.监听
listen(sfd,128);
printf("开始监听客户端连接情况>>>>>\n");
//4.接收客户端地址消息结构体
struct sockaddr_in cli;
socklen_t socklen=sizeof(cli);
int newfd=accept(sfd,(struct sockaddr*)&cli,&socklen);
printf("客户:[%s: %d]连接成功\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
//5.收发数据
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
recv(newfd,buf,sizeof(buf),0);
printf("[%s: %d]:%s\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port),buf);
if(strcmp(buf,"quit")==0)
{
printf("客户[%s: %d]已下线!\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
break;
}
}
//6.关闭套接字
close(newfd);
close(sfd);
return 0;
}
客户端:
//tcp客户端
#include
#define PORT 8888
#define IP "192.168.125.6"
int main(int argc, const char *argv[])
{
//1.创建套接字
int cfd=socket(AF_INET,SOCK_STREAM,0);
//2.连接服务端
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(PORT);
ser.sin_addr.s_addr=inet_addr(IP);
connect(cfd,(struct sockaddr*)&ser,sizeof(ser));
printf("已连接服务器!\n");
//3.收发数据
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
printf("请输入内容:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
send(cfd,buf,sizeof(buf),0);
if(strcmp(buf,"quit")==0)
break;
}
//4.关闭套接字
close(cfd);
return 0;
}
效果:
2.udp实现通信
服务器:
//udp服务器
#include
#define PORT 9999
#define IP "192.168.125.6"
int main(int argc, const char *argv[])
{
//1.创建套接字
int sfd=socket(AF_INET,SOCK_DGRAM,0);
//2.绑定服务器
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(PORT);
ser.sin_addr.s_addr=inet_addr(IP);
bind(sfd,(struct sockaddr*)&ser,sizeof(ser));
printf("服务器已上线! 等待连接中>>>>>\n");
//3.收发数据
char buf[128]="";
struct sockaddr_in cli;
socklen_t socklen=sizeof(cli);
while(1)
{
bzero(buf,sizeof(buf));
recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cli,&socklen);
printf("客户[%s: %d]:%s\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port),buf);
if(strcmp(buf,"quit")==0)
{
printf("客户[%s: %d]已下线!\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
break;
}
}
//4.关闭套接字
close(sfd);
return 0;
}
客户端:
//udp客户端
#include
#define PORT 9999
#define IP "192.168.125.6"
int main(int argc, const char *argv[])
{
//1.创建套接字
int cfd=socket(AF_INET,SOCK_DGRAM,0);
//2.收发数据
char buf[128]="";
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(PORT);
ser.sin_addr.s_addr=inet_addr(IP);
while(1)
{
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&ser,sizeof(ser));
if(strcmp(buf,"quit")==0)
break;
}
//3.关闭套接字
close(cfd);
return 0;
}
效果: