前段时间发了个TCP通信的例子,现在再来一个UDP通信的例子。这些可以作为样本程序,用到开发中。“裸写”socket老是记不住步骤,经常被鄙视……
下面的例子很简单,写一个UDP的server用于收包,写一个UDP的client用于发包并接收来自server的回复。其中UDP的client写了两个,一个是不需要connect的,另一个是带上connect的,两个client实现的功能是一样的。从效率上,带上connect的UDP肯定效率稍微高一些。不过UDP的connect和TCP里面非常不一样。在UDP里面connect的时候并没有三次握手的过程,但是它指定了与自己通信的对方的具体地址,内核中会将次地址记录下来,如果你的UDP就是在确定了两台机器之间传送信息,建议选取带有connect的套接字。connect之后与对方通信直接write或者read函数就可以,不用再指定对方ip和port,并且connect之后的套接字可以自动过滤掉不是来自指定通信方的信息。UDP可以调用多次connect函数,但是TCP套接字只能调用一次,再次调用会出现错误。
1. 首先是服务端的程序:
UDPserver.cpp
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h> #define PORT 1234
#define MAXDATASIZE 100 int main(void)
{
int sockfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t len;
int num;
char buf[MAXDATASIZE];
if((sockfd = socket(AF_INET, SOCK_DGRAM, )) == -)
{
perror("Creating socket failed.\n");
exit();
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -)
{
perror("Bind() error.\n");
exit();
} len = sizeof(client);
while()
{
num = recvfrom(sockfd, buf, MAXDATASIZE, , (struct sockaddr *)&client, &len);
if(num < )
{
perror("recvfrom() error.\n");
exit();
}
buf[num] = '\0';
printf("You got a message <%s> from client. \nIt's ip is %s, port is %d. \n", buf, inet_ntoa(client.sin_addr),htons(client.sin_port));
sendto(sockfd, "Welcome\n", , , (struct sockaddr *)&client, len);
if ( !strcmp(buf, "bye") ){
break;
}
}
close(sockfd);
}
2. 然后,我们给出带有connect的客户端程序:
UDPclientWithConnect.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h> #define PORT 1234 #define MAXDATASIZE 100 int main(int argc, char *argv[])
{
int sockfd, num;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server, peer;
if(argc != )
{
printf("Usage: %s <IP address> <message>\n", argv[]);
exit();
} if((sockfd=socket(AF_INET, SOCK_DGRAM, )) == -)
{
printf("socket() error\n");
exit();
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT); server.sin_addr.s_addr = inet_addr(argv[]);
//server.sin_addr.s_addr = inet_addr(argv[1]);
if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -)
{
printf("connect() error.\n");
exit();
} send(sockfd, argv[], strlen(argv[]), ); while()
{
if((num = recv(sockfd, buf, MAXDATASIZE, )) == -)
{
printf("recv() error.\n");
exit();
} buf[num] = '\0';
printf("Server Message: %s.\n", buf);
break;
}
close(sockfd);
}
3. 最后,再给一个不带connect的客户端程序。
UDPclientNoConnect.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> #define PORT 1234 #define MAXDATASIZE 100 int main(int argc, char *argv[])
{
int sockfd, num;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server, peer;
if(argc != )
{
printf("Usage: %s <IP address> <message>\n", argv[]);
exit();
}
if((he = gethostbyname(argv[]))==NULL)
{
printf("gethostbyname() error\n");
exit();
}
if((sockfd=socket(AF_INET, SOCK_DGRAM, )) == -)
{
printf("socket() error\n");
exit();
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *( (struct in_addr *)he->h_addr);
sendto(sockfd, argv[], strlen(argv[]), , (struct sockaddr *)&server, sizeof(server));
socklen_t len;
len = sizeof(server);
while()
{
if((num = recvfrom(sockfd, buf, MAXDATASIZE, , (struct sockaddr *)&peer, &len)) == -)
{
printf("recvfrom() error\n");
exit();
}
if(len != sizeof(server) || memcmp((const void *)&server, (const void *)&peer, len) != )
{
printf("Receive message from other server.\n");
continue;
}
buf[num] = '\0';
printf("Server Message: %s.\n", buf);
break;
}
close(sockfd);
}
执行一下命令进行编译:
$ g++ -o UDPserver UDPserver.cpp
$ g++ -o UDPclient2 UDPclientWithConnect.cpp
$ g++ -o UDPclient1 UDPclientNoConnect.cpp
完了以后就看到三个可执行文件了。
打开一个命令行,执行./UDPserver启动服务端程序,再打开另外一个命令行,执行./UDPclient1 127.0.0.1 "nihaonihao"或者./UDPclient2 127.0.0.1 "testtest"即可查看到以下效果:
[horstxu@vps ~/Cprog/udpCSmodel]$ ./UDPserver
You got a message <nihaonihao> from client.
It's ip is 127.0.0.1, port is 25595.
You got a message <testtest> from client.
It's ip is 127.0.0.1, port is 27396.
[horstxu@vps ~/Cprog/udpCSmodel]$ ./UDPclient1 127.0.0.1 "nihaonihao"
Server Message: Welcome
.
[horstxu@vps ~/Cprog/udpCSmodel]$ ./UDPclient2 127.0.0.1 "testtest"
Server Message: Welcome
.
[horstxu@vps ~/Cprog/udpCSmodel]$
最后再来解释一个带有connect的UDP的好处。由于UDP是不可靠传输,如果我发了数据出去,对方其实服务器是关闭的,这时会有什么结果呢?对于刚才的UDPclient1,也就是不带connect的,客户端程序会卡在recvfrom这里,因为对方是关闭的,它永远也收不到来自对方的回包。但是对于UDPclient2,也就是带有connect,我们其实可以收到一个错误,并设置errno(errno:111,connection refused)。这样看上去就比卡死在那里友好多了。对于这个问题的具体分析可以参考这篇文章:
[horstxu@vps ~/Cprog/udpCSmodel]$ ./UDPclient2 127.0.0.1 "testtest"
recv() error.
[horstxu@vps ~/Cprog/udpCSmodel]$ ./UDPclient1 127.0.0.1 "testtest"
#注释:程序在这里卡死