1. udp使用select
/*
*端口使用一个16位的数字表示,范围0~65535, 1024一下端口保留
*低位先存:起始地址放在低位字节
*高位先存:起始地址放在高位字节
*Intel CPU:地位先存
*TCP/IP使用16位和32位整数的高位先存格式
*/
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
return -1;
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return -1;
}
fd_set rfd;
timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
int nRet;
SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
char recvBuf[100];
for (;;)
{
FD_ZERO(&rfd);
FD_SET(sockSrv, &rfd);
nRet = select(0, &rfd, 0, 0, &timeout);
if (nRet < 0)
{
return -1;
}
else if (nRet == 0)
{
printf("timeout\n");
closesocket(sockSrv);
return 0;
}
else
{
if (FD_ISSET(sockSrv, &rfd))
{
recvfrom(sockSrv, recvBuf, 100, 0,(SOCKADDR*)&addrClient, &len);
printf("%s\n", recvBuf);
}
}
}
WSACleanup();
return 0;
}