Linux UDP C/S例子
UDP C/S編程的步驟如下圖所示
與TCP C/S通信的區別在於:
服務端沒有設置監聽和等待連接的過程。客戶端沒有連接服務端的過程。
基於UDP的通信時不可靠地,面向無連接的,發送的數據無法確切知道對方收到沒有,就算對方根本不存在,也可以發送數據出去。
這樣的通信通常用在對可靠性、安全性要求不高的地方,比如語音通信(沒聽清楚可以讓對方再說一遍)。
#include <sys/types.h>
#include <sys/socket.h>
#include<pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: %s port\n", argv[0]);
exit(1);
}
printf("Welcome! This is a UDP server, I can only received message from client and reply with same message\n");
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = htonl(INADDR_ANY);
int sock;
if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(1);
}
char buff[512];
struct sockaddr_in clientAddr;
int n;
int len = sizeof(clientAddr);
while (1)
{
n = recvfrom(sock, buff, 511, 0, (struct sockaddr*)&clientAddr, &len);
if (n>0)
{
buff[n] = 0;
printf("%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff);
n = sendto(sock, buff, n, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
if (n < 0)
{
perror("sendto");
break;
}
}
else
{
perror("recv");
break;
}
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<netinet/in.h>
#include <errno.h>
int main(int argc,char **argv)
{
int sockfd;
int addrlen,n;
struct sockaddr_in addr_ser;
char recvline[200],sendline[200];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
{
printf("socket error:%s\n",strerror(errno));
return -1;
}
bzero(&addr_ser,sizeof(addr_ser));
addr_ser.sin_family=AF_INET;
addr_ser.sin_addr.s_addr=htonl(INADDR_ANY);
addr_ser.sin_port=htons(atoi(argv[1]));
addrlen=sizeof(addr_ser);
while(1)
{
printf("Input your words: ");
scanf("%s",sendline);
n=sendto(sockfd,sendline,200,0,(struct sockaddr *)&addr_ser,addrlen);
if(n==-1)
{
printf("sendto error:%s\n",strerror(errno));
return -1;
}
printf("waiting for server......\n");
n=recvfrom(sockfd,recvline,200,0,(struct sockaddr *)&addr_ser,&addrlen);
if(n==-1)
{
printf("recvfrom error:%s\n",strerror(errno));
return -1;
}
recvline[n]='\0';
printf("recv data is:%s\n",recvline);
}
return 0;
}