llk
llk

Reputation: 2561

Receiving multiple messages Winsock2 C++

I am trying to make a program using Winsock2 where I can send a message from client to server. I can do this, but the problem is I can only send one message and then I have to restart the server to receive the next message. Here is the code for the server. The part I am really confused about is I have the recv() function in a while loop so why isn't it continuing to "receive" data?

   WSADATA wsaData;
    int bytes_recieved;
    char data_recieve[2048];
    string output;

    WSAStartup(MAKEWORD(2, 2), &wsaData);
    SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    SOCKADDR_IN ServerInfo;
    ServerInfo.sin_family = AF_INET;
    ServerInfo.sin_addr.s_addr = INADDR_ANY;
    ServerInfo.sin_port = htons(8888);

    bind(ListenSocket, (LPSOCKADDR)&ServerInfo, sizeof(struct sockaddr));
    listen(ListenSocket, 1);
    SOCKET ClientSocket = accept (ListenSocket, NULL, NULL);

    while(true)
    {
        bytes_recieved = recv(ClientSocket, data_recieve, 2048, 0);
            if (bytes_recieved > 1)
            {
                cout << data_recieve;
            }
    }

    closesocket(ClientSocket);
    closesocket(ListenSocket);
    WSACleanup();

The client (sender) is listed below.

WSADATA wsaData;
int bytes_sent;
char send_msg[] = "super cool message!";

WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in ConnectInfo;

ConnectInfo.sin_family = AF_INET;
ConnectInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
ConnectInfo.sin_port = htons(8888);

connect(ConnectSocket, (SOCKADDR*)&ConnectInfo, sizeof(ConnectInfo));
bytes_sent = send(ConnectSocket, send_msg, sizeof(send_msg), 0);
closesocket(ConnectSocket);
WSACleanup();

I am doing this in Windows 7 with a MinGW compiler. Thank you in advance.

Upvotes: 0

Views: 1774

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

You did not show your client sending code, but offhand, your server reading code is not taking into account that sends and receives are NOT 1-to-1 in TCP/IP programming. If a client sends 2 messages, the server may receive both messages, or even portions of them, in the same read operation! You ae telling your server socket to read 2048 bytes at a time. It will return whatever is currently available on the socket at that moment. TCP/IP is a byte stream, you need to treat it as much. That means you need to either put a delimiter in between your messages, or put a frame around them, in order to know where one message ends and the next message begins.

Upvotes: 2

Related Questions