LinuxC++的UDP服务器和客户端通信
服务器
#include<sys/socket.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
int main()
{int ret;int sfd=socket(AF_INET,SOCK_DGRAM,0);if(sfd==-1)perror("socket error");struct sockaddr_in saddr;saddr.sin_port=htons(8888);saddr.sin_family=AF_INET;saddr.sin_addr.s_addr=INADDR_ANY;ret=bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr));if(ret==-1)perror("bind error");char buffer[1024]={'\0'};while(true){struct sockaddr_in caddr;int caddrlen=sizeof(caddr);ret=recvfrom(sfd,buffer,1024,0,(struct sockaddr*)&caddr,(socklen_t*)&caddrlen);if(ret==-1){perror("recvfrom error");break;}else if(ret==0){printf("连接断开\n");break;}else{char ip[30]={'\0'};inet_ntop(AF_INET,&caddr.sin_addr.s_addr,ip,sizeof(ip));printf("从客户端%s:%d收到数据:%s\n",ip,htons(caddr.sin_port),buffer);char sendbuf[50]={'\0'};sprintf(sendbuf,"server recive your data:%s",buffer);ret=sendto(sfd,sendbuf,sizeof(sendbuf),0,(struct sockaddr*)&caddr,caddrlen);if(ret==-1){perror("sendto error");break;}}memset(buffer,0,1024);}close(sfd);return 0;
}
客户端
#include<sys/socket.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
int main()
{int ret;int cfd=socket(AF_INET,SOCK_DGRAM,0);if(cfd==-1)perror("socket error");struct sockaddr_in caddr;caddr.sin_port=htons(8888);caddr.sin_family=AF_INET;ret=inet_pton(AF_INET,"192.168.101.231",&caddr.sin_addr.s_addr);if(ret==-1)perror("inet_pton error");char buffer[1024]={'\0'};int i=0;while(true){char sendbuf[50]={'\0'};sprintf(sendbuf,"this is client:hello world:%d",i);ret=sendto(cfd,sendbuf,sizeof(sendbuf),0,(struct sockaddr*)&caddr,sizeof(caddr));if(ret==-1){perror("sendto error");break;}ret=recvfrom(cfd,buffer,1024,0,NULL,NULL);if(ret==-1){perror("recvfrom error");break;}else if(ret==0){printf("连接断开\n");break;}else{printf("收到了数据:%s\n",buffer);}memset(buffer,0,1024);memset(sendbuf,0,50);sleep(1);}close(cfd);return 0;
}