尝试在Qt中实现多线程服务器,只需考虑以下问题:
在SocketThread类中:
SocketThread::SocketThread(qintptr descriptor, QObject *parent)
: QThread(parent), socketDescriptor(descriptor)
{
socket = new QTcpSocket();
socket->setSocketDescriptor(socketDescriptor);
socket->moveToThread(this);
connect(socket, &QTcpSocket::readyRead, [this]() { qDebug() << socket->readAll(); }); //trying to read messages from clients
}
在连接类中: 在incomingConnection()
void Connection::incomingConnection(qintptr socketDescriptor)
{
SocketThread *socketThread = new SocketThread(socketDescriptor);
socketThread->start();
connect(socketThread, &SocketThread::started, [&]() { socketThread->socket->write("Hello!"); }); //write a message to client when thread is created
}
奇怪的是,如果我添加这一行:
connect(socketThread,&SocketThread :: started,&{socketThread-> socket-> write(“ Hello!”);}); //创建线程后向客户端发送消息
然后套接字将不会从客户端读取消息。如果我删除该行,套接字将读取客户端的消息。
我希望服务器在创建线程时向客户端发送消息,以及从客户端读取消息。如何解决该问题?
编辑:
SocketThread头文件:
class SocketThread : public QThread
{
Q_OBJECT
public:
SocketThread(qintptr descriptor, QObject *parent = 0);
~SocketThread();
QTcpSocket *socket;
qintptr socketDescriptor;
};
在Connection构造函数中:
Connection::Connection(QObject *parent) : QTcpServer(parent)
{
this->listen(QHostAddress::Any, 6666);
}
并在main.cpp
文件中创建一个连接对象。真的就像所有代码一样。