UDP是无连接的。
UDP Server网络编程基本步骤
- 创建socket,指定使用UDP协议
- 将socket与地址和端口绑定
- 使用recv/send接收/发送数据
由于UDP是无连接的,直接侦听就行 - 使用close关闭连接
这个UDP接收数据的时候用的API是recvfrom,发送数据是sendto
客户端
#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>
#include <arpa/inet.h>int main(int argc, char * *argv)
{struct sockaddr_in addr;socklen_t addrlen = sizeof(addr);int sock;addr.sin_family = AF_INET;addr.sin_port = htons(9876);addr.sin_addr.s_addr = inet_addr("127.0.0.1");char buff_send[512] = "Hello";char buff_recv[512] = {0};int len = sizeof(addr);int n = 0;printf("This is a UDP client\n");if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0){printf("socket error.\n");exit(1);}if (addr.sin_addr.s_addr == INADDR_NONE){printf("Incorrect ip address!");close(sock);exit(1);}n = sendto(sock, buff_send, strlen(buff_send), 0, (struct sockaddr *) &addr, sizeof(addr));if (n < 0){printf("sendto error.\n");close(sock);}n = recvfrom(sock, buff_recv, 512, 0, (struct sockaddr *) &addr, &addrlen);if (n > 0){buff_recv[n] = 0;printf("received from sever:");puts(buff_recv);}else if (n == 0)printf("server closed.\n");else if (n == -1)printf("recvfrom error.\n");close(sock);return 0;
}
服务器端
#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>
#include <arpa/inet.h>int main(int argc, char * *argv)
{struct sockaddr_in addr;addr.sin_family = AF_INET;addr.sin_port = htons(9876);addr.sin_addr.s_addr = INADDR_ANY;char buff_recv[512] = {0};char buff_send[512] = "world";struct sockaddr_in clientAddr;socklen_t addrlen = sizeof(clientAddr);int n;int len = sizeof(clientAddr);int sock;printf("Welcome! This is a UDP server.\n");if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0){printf("socket error.\n");exit(1);}if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0){printf("bind error.\n");exit(1);}while (1){//ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,struct sockaddr *src_addr, socklen_t *addrlen);n = recvfrom(sock, (void *)buff_recv, 511, 0, (struct sockaddr *) &clientAddr, &addrlen);if (n > 0){buff_recv[n] = 0;printf("recv data from client:%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff_recv);n = sendto(sock, (void *)buff_send, n, 0, (struct sockaddr *) &clientAddr, sizeof(clientAddr));if (n < 0){printf("sendto error.\n");break;}else {printf("recv error.\n");break;}}}return 0;
}