基于UDP的回声服务器/客户端
程序员文章站
2024-03-23 10:31:28
...
//服务器端代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAXN 1024
void error_handling(const char *str)
{
fputs(str,stderr);
fputc('\n',stderr);
exit(1);
}
int main(int argc,char *argv[])
{
int serv_sock;
int n=5,str_len;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
char msg[MAXN];
if(argc!=2)
{
printf("Usage:%s <port>\n",argv[0]);
exit(1);
}
serv_sock=socket(PF_INET,SOCK_DGRAM,0); //第一步:注意是SOCK_DGRAM
if(serv_sock==-1)
error_handling("socket() error");
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1) //第二步
error_handling("bind() error");
while(n--)
{
clnt_addr_size=sizeof(clnt_addr);
str_len=recvfrom(serv_sock,msg,MAXN,0,(struct sockaddr*)&clnt_addr,&clnt_addr_size); //接收数据
sendto(serv_sock,msg,str_len,0,(struct sockaddr*)&clnt_addr,clnt_addr_size); //发送数据
}
close(serv_sock);
return 0;
}
//客户端代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAXN 1024
void error_handling(const char *str)
{
fputs(str,stderr);
fputc('\n',stderr);
exit(1);
}
int main(int argc,char *argv[])
{
int clnt_sock,str_len;
struct sockaddr_in serv_adr,from_adr;
socklen_t from_adr_sz;
char msg[]="HelloWorld";
char store[1024];
if(argc!=3)
{
printf("ERROR\n");
exit(1);
}
clnt_sock=socket(PF_INET,SOCK_DGRAM,0); //第一步
if(clnt_sock==-1)
error_handling("socket() error");
memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=inet_addr(argv[1]);
serv_adr.sin_port=htons(atoi(argv[2]));
str_len=sendto(clnt_sock,msg,strlen(msg),0,(struct sockaddr*)&serv_adr,sizeof(serv_adr)); //发送数据
from_adr_sz=sizeof(from_adr);
recvfrom(clnt_sock,store,str_len,0,(struct sockaddr*)&from_adr,&from_adr_sz); //接收数据
store[str_len]='\0';
printf("Message from server: %s\n",store);
close(clnt_sock);
return 0;
}