Click here to Skip to main content
15,889,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!
I have a UDP server (source code is attached). "cout << "end";" line doesn't execute. Packets are received and are printed to screen but after closing client socket (in client code) server does not exit from while loop.
Can anyone help me?

C++
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include "iostream"
#include "conio.h"
#include "windows.h"
#include "winsock2.h"
#include "string"

#pragma comment(lib, "Ws2_32.lib")

using namespace std;

int main()
{
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2,2);
    int startup_RetVal = WSAStartup(DllVersion, &wsaData);
    SOCKET sSocket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    SOCKADDR_IN addr;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2222);
    bind(sSocket,(SOCKADDR*)&addr, sizeof(addr));
    char buf[400] = {0};
    while (recvfrom(sSocket, buf, 400, NULL, NULL, NULL) > 0)
    {
	cout << buf;
    }
    cout << "end";
    _getch();
    return 0;
}
Posted
Updated 18-Mar-14 1:12am
v2

1 solution

UDP is a connectionless protocol. So your server will not detect that the client has closed his connection and recvfrom will never return with a value of zero.

How to solve this problem depends on what you want to do. You can switch to a connection oriented protocol or implement your own transfer protocol that handles specific packets as "hangup" command.
 
Share this answer
 
Comments
Member 10674315 18-Mar-14 7:38am    
Ok. Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900