最近,我一直在尝试制作一个可以接受多个客户端的套接字服务器。我正在使用基本线程(并且我不想使用boost库)。但是我每次都会收到'term does not evaluate to a function taking 0 arguments thread sockets'错误,这是由于线程。如果我评论该线程,它确实可以工作。

有人可以帮助我吗?

这是代码:

#include <WinSock2.h>
#include <stdio.h>
#include <thread>

#define BUFFER_SIZE 1024

class TcpClient {
private:
    SOCKET s;
    SOCKADDR_IN a;
    std::thread t;
public:
    TcpClient(SOCKADDR_IN addr, SOCKET client) {
        this->s = client;
        this->a = addr;

        this->t = std::thread(&TcpClient::receiving_func);
        this->t.join();
    }

    void receiving_func(void* v) {
        for (;;) {
            char* data = new char[BUFFER_SIZE];
            int bytes = recv(this->s, data, BUFFER_SIZE, 0);
            std::string raw = std::string(data);
            raw = raw.substr(0, bytes);
            printf_s("Received %s\n", raw);
        }
    }
};

最佳答案

receiving_func(void* v)接受1个参数,但是std::thread(&TcpClient::receiving_func);需要一个接受零参数的函数。您认为v将在函数中使用什么?

您也许可以使用std::thread(&TcpClient::receiving_func, NULL);进行编译(并设置v == NULL),或者由于您没有使用v,只需将其从方法签名中删除即可。

另外,由于receiving_func是一个对象方法(它不是静态的),因此这是一个问题,因为无法识别this值。您可能希望使该函数静态化,将其参数设置为TcpClient *,并使用std::thread(&TcpClient::receiving_func, this);创建线程,最后,使用该参数而不是this来访问对象成员(因为静态方法上没有this)。

09-10 04:56
查看更多