使用Threads c ++时套接字无法正确打开

时间:2014-07-28 20:13:58

标签: c++ multithreading sockets winsock

嘿试图用套接字和线程进行分析。 我试图做一个小程序,从一个线程接受客户端,并将客户端的消息添加到队列中。并从另一个线程打印消息到控制台。

但出于某种原因,当我将进程拆分为2个线程时,套接字未正确打开,并且listen函数在WSAGetLastError上返回10022错误。

源代码:

void SlaveThread(queue<char*>* tasks);
void MasterThread(queue<char*>* tasks);

int _tmain(int argc, _TCHAR* argv[])
{
    queue<char*>* tasksQueue = new queue<char*>();

    thread SecondThread(MasterThread,tasksQueue);
    thread FirstThread(SlaveThread,tasksQueue);

    FirstThread.join();
    SecondThread.join();
    return 0;
};


void SlaveThread(queue<char*>* tasks)
{
    while (true)
    {
        if (!tasks->empty())
        {
            cout << tasks->front() << " Queue size : " << tasks->size() << endl;
            tasks->pop();
        }

        Sleep(1000);
    }
};

void MasterThread(queue<char*>* tasks)
{
    WSAData WinSockData;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &WinSockData);

    /* Create socket structure */
    SOCKADDR_IN Server;
    Server.sin_addr.s_addr = inet_addr("10.0.0.7");
    Server.sin_family = AF_INET;
    Server.sin_port = htons(27015);

    SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, NULL);
    SOCKET Connect;
    bind(ListenSock, (SOCKADDR*)&Server, sizeof(Server));
    listen(ListenSock, 1);
    int errno1 = WSAGetLastError();
    cout << "Listening on port 27015" << endl;
    //char buffer[200];
    int size = sizeof(Server);
    while (true)
    {
        if (Connect = accept(ListenSock, (SOCKADDR*)&Server, &size)){
            int errno1 = WSAGetLastError();
            cout << "Connection established.. " << endl;
        }
        //if (recv(ListenSock, buffer, 200, 0) > 0)
        //{
        //  tasks->push(buffer);
        //}
    }

    WSACleanup();
};

当我向程序添加线程时,为什么它会中断?因为在空程序中只需用相同的代码打开套接字就可以正常工作。

1 个答案:

答案 0 :(得分:2)

1)使用INADDR_ANY 2)使用:: bind而不是bind。该名称对标准模板库调用不明确。这就是使用命名空间std不好的原因。

void MasterThread(queue<char*>* tasks)
{
    WSAData WinSockData;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &WinSockData);

    /* Create socket structure */
    SOCKADDR_IN Server;
    Server.sin_addr.s_addr = INADDR_ANY;//inet_addr("10.0.0.7");
    Server.sin_family = AF_INET;
    Server.sin_port = htons(27015);

    SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, NULL);
    SOCKET Connect;
    ::bind(ListenSock, (SOCKADDR*)&Server, sizeof(Server));
    int errno0 = WSAGetLastError();
    listen(ListenSock, 1);
    int errno1 = WSAGetLastError();
    cout << "Listening on port 27015" << endl;
    //char buffer[200];
    int size = sizeof(Server);
    while (true)
    {
        if (Connect = accept(ListenSock, (SOCKADDR*)&Server, &size)){
            int errno1 = WSAGetLastError();
            cout << "Connection established.. " << endl;
        }
        //if (recv(ListenSock, buffer, 200, 0) > 0)
        //{
        //  tasks->push(buffer);
        //}
    }

    WSACleanup();
};