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

C++ socket server doesn't accept any clients / client won't connect

我有一个简单的 class 启动服务器并监听客户端,在他们连接后为他们启动一个线程,我的问题是当我 运行 服务器似乎是监听,当我尝试使用简单的 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 在我的客户端上,服务器一直在监听。

我的问题是我忘了把端口放在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);

    }

}