说道UDP,大家自然先想到TCP,那我们就先来比较比较着两种的特性!
TCP | UDP | |
应用场合 | 传输数据量大 | 传输数据量小 |
传输速度 | 慢 | 快 |
传输可靠性 | 可靠 | 不可靠 |
连接性 | 面向连接 | 无连接 |
UDP类型是数据报套接字(SOCK_DGRAM);
服务器的启动流程:socket --> bind -- > sendto/recvform --> closesocket
客户端的启动流程:socket --> sendto/recvfrom --> closesocket
这样看,UDP通信其实比较简单!
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
WSADATA wsa_data;
int ret = 0;
ret = WSAStartup(MAKEWORD(2,2),&wsa_data); //初始化正确返回0
SOCKADDR_IN server_addr;
SOCKET fd_socket;
fd_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //出错则返回 INVALID_SOCKET
SOCKADDR_IN client;
int client_len = 0;
char buff[1024];
memset(buff,0x0,1024);
ret = recvfrom(fd_socket,buff,1024,0,(SOCKADDR *)&client,&client_len);
char send_buff[512];
memset(send_buff,0x0,512);
ret = sendto(fd_socket,send_buff,strlen(send_buff),0,(SOCKADDR *)&client,client_len);
closesocket(fd_socket);
WSACleanup();
有上面的流程可以看出,UDP的客户端与服务器只是少了一个绑定操作!
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
WSADATA wsa_data;
int ret = 0;
ret = WSAStartup(MAKEWORD(2,2),&wsa_data); //初始化正确返回0
SOCKADDR_IN server_addr;
SOCKET fd_socket;
fd_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //出错则返回 INVALID_SOCKET
int server_len = 0;
char buff[1024];
memset(buff,0x0,1024);
ret = recvfrom(fd_socket,buff,1024,0,(SOCKADDR *)&server_addr,&server_len);
char send_buff[512];
memset(send_buff,0x0,512);
ret = sendto(fd_socket,send_buff,strlen(send_buff),0,(SOCKADDR *)&server_addr,server_len);
closesocket(fd_socket);
WSACleanup();
请大家多多指教!