我在本機創建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;
}
UDP協議本身就是無連接不可靠的協議,丟失幾個包很正常,TCP協議雖然也基於無連接不可靠的IP協議,但是他有嚴密的校驗,超時重發機制,一般不會出現丟失包的問題