0

我正在使用 VC++ 2012 Express 创建一个多线程聊天客户端服务器。代码改编自这里: http: //www.codeproject.com/Articles/14032/Chat-Client-Server

服务器似乎工作正常。然而,不知何故,客户端无法启动线程来接收消息。该GetLastError()函数在调用时返回 8。

这是客户端代码的片段:

#include "Chatter_Client.hpp"

CMessenger MessObj;
//... CMessenger::Init initializes Winsock, socket, and connection.
int CMessenger::RecMessage()
{
    char buffRetData[4096];
    int stat;

    stat = recv(conn, buffRetData, 4096, 0);
    if(stat == -1) {
        cout << "Message not received!" << endl;
        return 1; // gagal
    } else {
        cout << "-->" << buffRetData << "\n";
        return 0; // looping lagi~
    }
}

DWORD WINAPI MessageRecThread(LPVOID pParam)
{
    for(;;) {
        Sleep(50);
        if(MessObj.RecMessage())
            break;
    }
    return 0;
}

int main()
{
    string buf;
    DWORD RecThreadID;

    string sServerAddress;
    int iPort;
    for(;;) {
        cout << "Server address: ";
        cin >> sServerAddress;
        if (sServerAddress.size() == 0) {
            cout << "No Address entered!" << endl;
        } else break;
    }
    cout << "Server port: ";
    cin >> iPort;

    MessObj.Init(sServerAddress.c_str(), iPort);
    if(!MessObj.IsConnected()) {
        cout << "Connection error!";
        _getch();
        return -1;
    }
    Sleep(30);

    HANDLE RecThread = CreateThread(NULL, 20000, MessageRecThread, NULL, 0, &RecThreadID);
    if(RecThread == NULL) {
        cout << "Listener thread cannot be created! ERROR CODE: " << GetLastError() << endl;
        _getch();
        return 1;
    } else {
        cout << "Yey masuk!" << endl;
    }
    for(;;) {
        cin >> buf;
        if(MessObj.SendMessage(buf)) {
            cout << "Connection lost!" << endl;
            break;
        }
    }
    cout << "Terminating client...";
    _getch();

    return 0;
}

和标题:

#include <cstdio>
#include <winsock2.h>
#include <conio.h>
#include <iostream>
#include <string>
#include <windows.h>

#pragma comment(lib, "WS2_32.lib")

using namespace std;

class CMessenger
{
public:
    CMessenger();
    ~CMessenger();
    void Init(string iIP, int iPort);
    int SendMessage(string sMessage);
    int RecMessage();
    bool IsConnected();
private:
    bool ConnStatus;
    string sIPAddress;
    int sPort;
    SOCKET conn;
};

我尝试使用 C++11 的<thread>,但是当线程类被调用时,调试器立即调用了abort().

有什么线索吗?

PS:此代码编译。

编辑

这是新的片段::Init,有一些编辑:

void CMessenger::Init(const string& iAddress, const string& iPort)
{
    // init winsock
    WSAData wsData;
    int stat = WSAStartup(MAKEWORD(2,0), &wsData);

    if (stat != 0) {
        cerr << "ERROR: WINCODE " << WSAGetLastError() << endl;
        return;
    }
    // get server info
    addrinfo hints, *res, *p_hints;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    stat = getaddrinfo(iAddress.c_str(), iPort.c_str(), &hints, &res);
    if(stat != 0) {
        cerr << "ERROR: " << gai_strerror(stat) << endl;
        return;
    }
    void *addr;
    char ipstr[INET6_ADDRSTRLEN];
    p_hints = res;
    sockaddr_in *ip = (struct sockaddr_in*)p_hints->ai_addr;
    addr = &(ip->sin_addr);
    
    // convert to string and print it
    inet_ntop(p_hints->ai_family, addr, ipstr, sizeof ipstr);
    cout << "Server IP: " << ipstr << endl;

    // init socket
    conn = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (conn == INVALID_SOCKET) {
        cout << "SOCKET ERROR\n";
        return;
    }

    // connect to server
    stat = connect(conn, res->ai_addr, res->ai_addrlen);
    if(stat != 0) {
        cerr << "ERROR: " << WSAGetLastError() << endl;
        return;
    }
    
    // connect OK
    sPort = atoi(iPort.c_str());
    sAddress = iAddress;
    cout << "Connection established." << endl << endl;
    ConnStatus = true;
    Sleep(30);
    return;
}

仍然有线程问题..

4

1 回答 1

2

Just tried your code, replacing missing methods with stubs, and it the tread was created without any problems. Make sure your MessObj::Init() method does no harm (memory corruption).

And one addition:

CMessanger
{
...
    void Init(string iIP, int iPort)
...
}


    string sServerAddress;
...
    MessObj.Init(sServerAddress.c_str(), iPort);

It is bad style - to many string object copies and string-> char* -> string conversion. If passed string is not 'copied' within CMessenger::Init() method then the method should be changed to

   void Init(const string& iIP, int iPort)

and call it

     MessObj.Init(sServerAddress, iPort);

if the string argument is copied within method then you still pass argument by value but use movable semantics within method like:

   void Init(string iIP, int iPort)
   {
         m_ip = std::move(iIP);
   }
于 2013-10-30T10:27:58.170 回答