//UDP receiver
int main()
{
WSAData wsaData;
SOCKET receivingSocket;
SOCKADDR_IN receiverAddr;
SOCKADDR_IN senderAddr;
int senderAddrSize = sizeof(senderAddr);
int port=51020;
char receiveBuf[1024];
int bufLength=1024;
cout << "UDP receiver\n";
//Initialize winsock
if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout << "Failed. Error Code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Initialised\n";`
if(receivingSocket = socket(AF_INET, SOCK_DGRAM, 0) == INVALID_SOCKET)
{
cout << "Could not create socket :" << WSAGetLastError();
}
cout << "Socket created.\n";
//fill up SOCKADDR_IN structure
senderAddr.sin_port = htons(port);
senderAddr.sin_family = AF_INET;
senderAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//Bind information with socket
bind(receivingSocket, (SOCKADDR*)&senderAddr, sizeof(senderAddr));
while(1)
{
cout << "Waiting for message\n";
//try to receive some data, this is a blocking call
if (recvfrom(receivingSocket, receiveBuf, 1024, 0, (SOCKADDR*)&senderAddr, &senderAddrSize)) == SOCKET_ERROR))
{
cout << "recvfrom() failed with error code :" << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << receiveBuf;
}
//Close socket
closesocket(receivingSocket);
WSACleanup();
std::cin.get();
return 0;
}
C++ socket編程:SENDTO()和recvfrom()錯誤代碼10038&在 '服務器' 綁定失敗與10038
//UDP server
int main()
{
WSAData wsaData;
SOCKET sendingSocket;
SOCKADDR_IN receiverAddr;
int port = 51010;
char sendBuf[1024]="Hello!!!";
int bufLength = 1024;
cout << "UDP server from book\n";
//Initialize socket
if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout << "Failed. Error Code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Initialised\n";
if(sendingSocket = socket(AF_INET, SOCK_DGRAM, 0) == INVALID_SOCKET)
{
cout << "Could not create socket : " << WSAGetLastError();
}
cout << "Socket created.\n";
//FIll out structure of receiverAdd
receiverAddr.sin_family = AF_INET;
receiverAddr.sin_port = htons(port);
receiverAddr.sin_addr.s_addr = inet_addr("192.168.1.100");
int test = bind(sendingSocket, (SOCKADDR*)&receiverAddr, sizeof(receiverAddr));
if(test < 0)
{
cout << "Bind failed with error code : %d" << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Bind is successful\n";
while(1)
{
cout << "Sending data...\n";
//Send datagram to receiver
if(sendto(sendingSocket, sendBuf, 1024, 0, (SOCKADDR*)&receiverAddr, sizeof(receiverAddr)) == SOCKET_ERROR)
{
cout << "sendto() failed with error code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Sent";
}
//close socket
closesocket(sendingSocket);
WSACleanup();
std::cin.get();
// return 0;
}
你忘了提問了。 – 2014-09-30 21:11:39
此代碼是可以格式化的。我爲您解決了這個問題,但下次請在發佈代碼片段時[學習如何正確格式化](http://stackoverflow.com/help/formatting)代碼片段。 – 2014-09-30 21:15:51
您還忘了查看Winsock錯誤10038. – EJP 2014-09-30 21:25:16