无法收听并连接winsock2

时间:2015-03-17 14:22:35

标签: c++ winsock winsock2

我的Windows套接字代码有问题,使用wxDev用C ++编写。以下代码的输出是:

Starting...
: Compatible...
: Created...
: Binding Done...
: Cannot listen...
: Error connecting...
:::Cleaned:::

我不知道为什么听和连接失败。

代码

void serverFrm::serverClick(wxCommandEvent& event)
{
    SOCKET sockh, socka;
    WSADATA wsadata;
    sockaddr_in sockAddr;

    if (WSAStartup(MAKEWORD(2, 2), &wsadata) == 0) {
        box->AppendText(_(" : Starting...\n"));
    }
    if (LOBYTE(wsadata.wVersion) >= 2) {
        box->AppendText(_(" : Compatible...\n"));
    }

    sockh = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockh != SOCKET_ERROR) {
        box->AppendText(_(" : Created...\n"));
    }
    else {
        box->AppendText(_(" : Error connecting...\n"));
    }

    sockAddr.sin_family = AF_INET;
    sockAddr.sin_port = htons(6788);
    sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    if (bind(sockh, (sockaddr*)(&sockAddr), sizeof(sockAddr)) != SOCKET_ERROR) {
        box->AppendText(_(" : Binding Done...\n"));
    }
    else {
        box->AppendText(_(" : Error binding...\n"));
    }

    if (listen(sockh, SOMAXCONN) != 0) {
        box->AppendText(_(" : Listening...\n"));
    }
    else {
        box->AppendText(_(" : Cannot listen...\n"));
    }

    int siz = sizeof(sockh);
    if (accept(sockh, reinterpret_cast<sockaddr*>(&sockAddr), &siz) != SOCKET_ERROR) {
        box->AppendText(_(" : Connected...\n"));
    }
    else {
        box->AppendText(_(" : Error connecting...\n"));
    }

    closesocket(sockh);
    if (WSACleanup() == 0)
        box->AppendText(_(":::Cleaned:::\n"));
}

1 个答案:

答案 0 :(得分:0)

if(listen(sockh, SOMAXCONN)!=0)

This function returns 0 when it succeeds。您的有条件检查是倒退的。

阅读文档,感谢Kahless对您的代码的正确压缩。