Moon
Moon

Reputation: 329

Winsock2 listen loop

Hello again wonderful stackoverflow community! Last time I asked a question, it was resolved quickly, right off the back and I hope this will go the same way. :)

So I'm toying with winsock, and I want to be able to connect multiple clients to my server simultaneously. I feel that this could be achieved with a loop on thread creation, socket creation, binding, and listening every time a client connects, but my efforts to do so have only turned up with "listen failed with error"'s. Two different ones depending on what I had tried. I googled it only to find the advanced MSDN samples the easiest, and still way too hard, examples out there. Anyone have any simple suggestions? (Side question: I can't seem to get "mrecv()" to return the whole "recvbuf" variable. All I get is one letter. I know this is a newbie mistake I'm making, but I just can't figure it out. :/ This problem can wait until later, however.)

(Here's the server code so far:)

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

int minitialize();
int msend(char msendbuf[512]);
char mrecv();
int mshutdown();

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "10150"
 WSADATA wsaData;
 int iResult;

 SOCKET ListenSocket = INVALID_SOCKET;
 SOCKET ClientSocket = INVALID_SOCKET;

 struct addrinfo *result = NULL;
 struct addrinfo hints;

 int iSendResult;
 char recvbuf[DEFAULT_BUFLEN];
 int recvbuflen = DEFAULT_BUFLEN;

int main(void) 
{
    minitialize();
    mrecv();

    char mmessage[512];
    if (strncmp(mmessage,"shutdown",(strlen(mmessage))) == 0) {mshutdown();}
    std::cin.getline(mmessage, 512);
    msend(mmessage);

    // shutdown the connection since we're done
    mshutdown();
    std::cin.ignore();

    return 0;
}

int msend(char msendbuf[512])   // Send a message
{
    int iResult3 = send( ClientSocket, msendbuf, 512, 0 );
    if (iResult3 == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);
            std::cout<<"msendbuf: "<<msendbuf<<"\n";
            std::cin.ignore();
}

char mrecv() //Recieve a message
{
    int iResult2 = recv(ClientSocket, recvbuf, 512, 0);
        if (iResult2 > 0) {
            printf("Bytes received: %d\n", iResult2);
        std::cout<<"recvbuf: "<<recvbuf<<"\n";
        }
        else if (iResult2 == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
    return *recvbuf;
}

int minitialize()   //initialize the winsock server
{
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);
}

int mshutdown()     //shutdown the server
{
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();
    return 0;
}

Yes, if you're wondering, I am planning on putting all those global variables in their respective local functions. I just need them there to clear a little clutter for now, and it doesn't seem to be causing any issues.

Upvotes: 0

Views: 2256

Answers (2)

alvits
alvits

Reputation: 6768

mrecv() is defined as

char mrecv().

In the function mrecv(), it returns a string. Because mrecv() by definition should return a char, the first char of recvbuf is returned. The compiler will not complain of return *recvbuf. This is syntactically correct even when the intent is to return a single character.

accept() returns a file descriptor to the client's connection. Upon return of accept(), you may spawn a new process to process the message using this descriptor while the original process goes back to accepting connections. Or you may create a new thread to process the message from this descriptor while the original thread resumes accepting connections. You will need to loop on accept().

Here's a skeletal template you can use for server. You already got everything correctly on minitialize(). In the sample code below, mrecv() accepts a parameter, the file descriptor of the connected client, newconn.

socket()
bind()
listen(mysock, 10);
while(keep listening) {
    newconn = accept(mysock, &peeraddr, &peeraddrlen)
    if(newconn > 0) {
        if(CreateThread(<security attribute>, <stack size>, (void *)&mrecv, (void *)&newconn, <creation flag>, <threadid>))
            perror("Unable to create thread\n");
    }
}
closesocket(mysock)

Upvotes: 1

user207421
user207421

Reputation: 311050

I feel that this could be achieved with a loop on thread creation, socket creation, binding, and listening every time a client connects

No. All you have to to is accept the client connection and start a thread with that socket. Leave the listening socket strictly alone. It isn't affected by the accept() operation and there is no need to rebuild it in any way.

Upvotes: 1

Related Questions