0

又回来了(对不起)

我创建了一个套接字 C++ 应用程序,但它不能正常工作。

这是我的第一个代码:

void Network::Start()
{
    this->socket = Env::GetSocket();

    SOCKADDR_IN sInformation;

    sInformation.sin_family = AF_INET;
    sInformation.sin_addr.s_addr = INADDR_ANY;
    sInformation.sin_port = htons(30000);

    bind(this->socket, (SOCKADDR*) (&sInformation), sizeof(sInformation));
    listen(this->socket, 10);

    while (true)
    {
        this->DO();
    }
}

和 DO 功能:

void Network::DO()
{
    SOCKET s = SOCKET_ERROR;

    sockaddr_in sock_addr;

    accept(s, (sockaddr*) &sock_addr, NULL);

    if (INVALID_SOCKET == s)
    {
        return;
    }
    else
    {
        cout << "Received connection from " << inet_ntoa(sock_addr.sin_addr);
    }
}

会发生什么,总是(即使我连接)值 s 是 INVALID_SOCKET。我通过 .SWF 连接,但它不接受我的连接。我究竟做错了什么?

4

2 回答 2

1

accept以监听socket为参数,返回新连接的socket;

socklen_t length = sizeof(sockaddr_in);
s = accept(this->socket, (sockaddr*) &sock_addr, &length);

编辑:刚刚测试了程序,清除了使用 AF_INET、SOCK_STREAM 和 sInformation 创建的套接字;

bzero((char *) &sInformation, sizeof(sInformation));

...它似乎在 MacOS X 和 linux 上运行良好。

于 2013-06-12T18:24:01.337 回答
1

您没有进行足够的错误处理,并且您没有accept()正确使用。尝试这个:

void Network::Start()
{
    this->socket = Env::GetSocket();
    if (this->socket == INVALID_SOCKET)
    {
        // error
        return;
    }

    SOCKADDR_IN sInformation = {0};

    sInformation.sin_family = AF_INET;
    sInformation.sin_addr.s_addr = INADDR_ANY;
    sInformation.sin_port = htons(30000);

    if (bind(this->socket, (SOCKADDR*) &sInformation, sizeof(sInformation)) != 0)
    {
        // error
        return;
    }

    if (listen(this->socket, 10) != 0)
    {
        // error
        return;
    }

    while (true)
    {
        this->DO();
    }
}

void Network::DO()
{
    SOCKADDR_IN sock_addr = {0};
    socklen_t sock_addr_len = sizeof(sock_addr);

    SOCKET s = accept(this->socket, (SOCKADDR*) &sock_addr, &sock_addr_len);
    if (INVALID_SOCKET == s)
    {
        return;
    }

    cout << "Received connection from " << inet_ntoa(sock_addr.sin_addr);

    // use s as needed. Don't forget to call close(s) or closesocket(s)
    // when finished, depending on your platform...
}
于 2013-06-12T21:50:44.050 回答