문제

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

도움이 되었습니까?

해결책

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;
}

다른 팁

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().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top