C ++套接字服务器不接受任何客户端/客户端将无法连接

时间:2019-06-29 18:40:28

标签: c++ sockets tcp winsockets

我有一个简单的类,用于启动服务器并侦听客户端,然后在客户端连接后为客户端启动线程,我的问题是,当我运行服务器时,它似乎正在侦听,并且尝试使用简单的python连接服务器不接受套接字的代码。

很明显,我认为问题出在客户端连接上,但是在尝试将地址从环回更改为我的本地地址后,我得到了相同的结果,所以我不确定是什么原因造成的。

服务器代码:

Communicator::Communicator()
{
    WSADATA wsaData;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        throw std::runtime_error("Failed to startup WSA");
    }

    m_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (m_sock == INVALID_SOCKET)
    {
        throw std::runtime_error("Failed to create socket");
    }
}


Communicator::~Communicator()
{
    try
    {
        WSACleanup();
        closesocket(m_sock);
    }
    catch (...) {}
}

void Communicator::bindAndListen()
{
    SOCKADDR_IN sa;
    sa.sin_port = Config::getConfig()["port"]; // 8080
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;

    if (bind(m_sock, (const SOCKADDR*) & sa, sizeof(sa)) == SOCKET_ERROR)
    {
        throw std::runtime_error("Failed to bind socket");
    }

    if (listen(m_sock, SOMAXCONN) == SOCKET_ERROR)
    {
        throw std::runtime_error("Failed to start listening");
    }

    std::cout << "Listening" << std::endl; // This gets printed
    while (true)
    {
        SOCKET clientSock = accept(m_sock, NULL, NULL); // Nothing accepted, program stuck here
        std::cout << "Connection" << std::endl;
        if(clientSock == INVALID_SOCKET)
        { 
            throw std::runtime_error("Invalid connection");
        }

        startThreadForNewClient(clientSock);

    }

}

测试python代码:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.connect(('127.0.0.1', 8080))
s.send(b"h")

我遇到的唯一错误是客户端上的[WinError 10061] No connection could be made because the target machine actively refused it,服务器一直在监听。

1 个答案:

答案 0 :(得分:0)

我的问题是我忘记将端口放在htons中,对不起我的菜鸟错误。

void Communicator::bindAndListen()
{
    SOCKADDR_IN sa;
    sa.sin_port = htons(Config::getConfig()["port"]); 
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;

    if (bind(m_sock, (const SOCKADDR*) & sa, sizeof(sa)) == SOCKET_ERROR)
    {
        throw std::runtime_error("Failed to bind socket");
    }

    if (listen(m_sock, SOMAXCONN) == SOCKET_ERROR)
    {
        throw std::runtime_error("Failed to start listening");
    }

    std::cout << "Listening" << std::endl;
    while (true)
    {
        SOCKET clientSock = accept(m_sock, NULL, NULL);
        std::cout << "Connection" << std::endl;
        if(clientSock == INVALID_SOCKET)
        { 
            throw std::runtime_error("Invalid connection");
        }

        startThreadForNewClient(clientSock);

    }

}