基于UDP的通信时不可靠地,面向无连接的,发送的数据无法确切知道对方收到没有,通常用于对可靠性要求不高的通信中,使用简单,UDP没有严格区分server端和client端,唯一的区别是绑不绑定(bind)端口。
1,接收程序(server)
#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> #define SERV_PORT 27350 int main(int argc, char **argv) { int sock_fd; char rcv_buff[512]; struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_len; int rcv_num = -1; if ((sock_fd = socket(AF_INET, SOCK_DGRAM,0)) < 0) { perror("socket create error "); exit(1); } memset(&server_addr,0,sizeof(struct sockaddr_in)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERV_PORT); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); client_len = sizeof(struct sockaddr_in); if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0) { perror("bind error. "); exit(1); } while (1) { rcv_num= recvfrom(sock_fd, rcv_buff, sizeof(rcv_buff), 0, (struct sockaddr*)&client_addr, &client_len); if (rcv_num>0) { rcv_buff[rcv_num] = '