Frage

I'm new to using winsock2 and have put together the following code for a server that I'm trying to use to send a string to a client that I'm running on the same computer (connecting to 127.0.0.1 with the same port as the server is set to listen on).

I'm using MinGW, if that matters.

The problem I'm having is that listen() seems to finish early but returning a success code. This is a problem because then when accept() is called it seems to block forever. This event happens whether or not I am running the client program, and I have tried running the client program before and after but this doesn't seem to affect it.

// -1: "Could not initialize WSA."
// -2: "Could not create listener socket."
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <cstdio>
#define port 0x0ABC
UINT64 trStrLen (char* str)
{
    if (str == NULL) return 0;
    UINT64 pos = 0;
    while (*(str + pos) != '\0') pos++;
    return pos;
};
#include <cstdio>
int main ()
{
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2,0),&wsadata)) return -1;
    SOCKET server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    SOCKADDR_IN sin;
    memset(&sin,0,sizeof(SOCKADDR_IN));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = INADDR_ANY;
    int socksize = sizeof(SOCKADDR);
    while (bind(server,(SOCKADDR*)(&sin),socksize) == SOCKET_ERROR) return -2;
    char* TEMP_TO_SEND = "Billy Mays does not approve.";
    UINT64 TEMP_SEND_LEN = trStrLen(TEMP_TO_SEND);
    printf("Server online.\n");
    while (true)
    {
        printf("Waiting for connections.\n");
        while (listen(server,SOMAXCONN) == SOCKET_ERROR);
        printf("Client requesting connection.\n");
        SOCKET client = accept(server,NULL,NULL);
        printf("Accept is no longer blocking.\n");
        if (client != INVALID_SOCKET)
        {
            printf("Attempting to send information to the client...\n");
            if (send(client,TEMP_TO_SEND,TEMP_SEND_LEN,0) == SOCKET_ERROR) printf("The information wasn't sent properly.\n");
            else printf("The client received the information.\n");
        }
        else printf("Couldn't establish a connection to the client.\n");
    };
};

It's probably something obvious, but I'm not seeing it, so any tips would be helpful.

War es hilfreich?

Lösung

listen() isn't a blocking call. It doesn't do anything to the network. It just puts the socket into passive listening mode, sets up the backlog queue, and returns. It is accept() that is the blocking call: it blocks until an incoming connection has been completed and then returns a socket for it.

So you shouldn't be calling listen() in a while loop at all.

Same applies to bind(). Call it once.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top