我在本机创建2个UDP程序,一个发送数据,另一个接收数据,可每次只能发送一次数据,第二次发送数据的时候那边就收不到了,是怎么回事啊,这是代码
#include
#include
#pragma comment(lib,"WS2_32.lib")
int main()
{
//初始化网络
WSADATA wsaData;
WORD wVersion = MAKEWORD(2, 2);
WSAStartup(wVersion,&wsaData);
//建立socket
SOCKET sServer = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//节点信息
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(16568);
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//绑定套接字到节点
if (bind(sServer, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
return 0;
}
//接收数据
char szBuf[1024];
SOCKADDR_IN addr;
int nlen = sizeof(addr);
while (1)
{
int nRecv = recvfrom(sServer,szBuf,strlen(szBuf),0,(SOCKADDR*)&addr,&nlen);
if (nRecv > 0)
{
szBuf[nRecv] = '\0';
printf("接收到的数据:%s\n",szBuf);
}
}
//关闭socket,释放网络
closesocket(sServer);
WSACleanup();
return 0;
}
这是另一个UDP程序
#include
#include
#pragma comment(lib,"WS2_32.lib")
int main()
{
//初始化网络
WSADATA wsaData;
WORD wVersion = MAKEWORD(2, 2);
WSAStartup(wVersion, &wsaData);
//建立socket
SOCKET sClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//目标节点信息
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(16568);
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//发送数据
char szBuf[1024];
while (1)
{
gets(szBuf);
if (strcmp(szBuf, "exit") == 0)
break;
sendto(sClient, szBuf, strlen(szBuf), 0, (SOCKADDR*)&sin, sizeof(sin));
}
//关闭socket,释放网络
closesocket(sClient);
WSACleanup();
return 0;
}