Question

I am making a C++ network application and I am creating the server,but I have a strange problem.When I call listen,it should wait for a connection,but the application continues like if the listen call doesn't exist.This is my code:

#include "includes.hpp"
using namespace std;
SOCKET sv;
WSADATA w;

int serverStart(int port)
{
    int error = WSAStartup(0x0202,&w);
    if(error)
    {
        fprintf(stderr,"Error de startup:%i",error);
        return false;
    }
    if(w.wVersion != 0x0202)
    {
        fprintf(stderr,"Error versión incorrecta de wsadata: Esperada 202.Obtenida %X",w.wVersion);
        WSACleanup();
        return false;
    }
    SOCKADDR_IN addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    sv = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(sv == INVALID_SOCKET)
    {
        fprintf(stderr,"Error de socket");
        return false;
    }
    if(bind(sv,(LPSOCKADDR)&addr,sizeof(addr)) == SOCKET_ERROR){
        fprintf(stderr,"Error de bind");
        return false;
    }
    fprintf(stdout,"Listen..");
    listen(sv,SOMAXCONN);
    fprintf(stdout,"Fin");
}

I am calling serverStart from main.I also have the firewall deactivated to see if it was the problem,but it didn't worked.

Thanks

Was it helpful?

Solution

The call to listen only places the socket in a state that accepts incomming connections. In order to actually accept a connection, you need to call the accept function. The call to accept blocks the program until you get a connection.

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

OTHER TIPS

listen() is not a blocking function. It just puts the socket into listening state. It is accept() that is the blocking function, and recv(), and send().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top