QTcpServer 多线程
时间: 2023-11-16 07:56:40 浏览: 278
QTcpSever服务器多线程示例
4星 · 用户满意度95%
QTcpServer是Qt中用于实现TCP服务器的类,它可以监听指定的端口并接受客户端的连接请求。在多线程中使用QTcpServer可以实现同时处理多个客户端的连接请求,提高服务器的并发性能。具体实现方法是继承QTcpServer类并重写incomingConnection函数,在该函数中为每个客户端连接分配一个新的线程,并将该连接交给该线程处理。在处理过程中,可以使用QTcpSocket类与客户端进行通信。同时,为了避免线程之间的资源竞争,需要使用QMutex等线程同步机制进行保护。
以下是一个简单的QTcpServer多线程实现的示例代码:
```
class MyTcpServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyTcpServer(QObject *parent = nullptr);
protected:
void incomingConnection(qintptr socketDescriptor) override;
signals:
void sentData(const QByteArray &data, int handle);
void sockDisConnect(int handle, QString ip, quint16 prot);
private slots:
void sockDisConnectSlot(int handle, QString ip, quint16 prot);
private:
QHash<int, MyTcpSocket*> tcpClient;
QMutex mutex;
};
void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
MyTcpSocket *tcpSocket = new MyTcpSocket(this);
tcpSocket->setSocketDescriptor(socketDescriptor);
QThread *thread = new QThread(this);
tcpSocket->moveToThread(thread);
connect(thread, &QThread::finished, tcpSocket, &QObject::deleteLater);
connect(this, &MyTcpServer::sentData, tcpSocket, &MyTcpSocket::sentData);
connect(tcpSocket, &MyTcpSocket::disconnected, thread, &QThread::quit);
connect(tcpSocket, &MyTcpSocket::disconnected, this, &MyTcpServer::sockDisConnectSlot);
mutex.lock();
tcpClient.insert(socketDescriptor, tcpSocket);
mutex.unlock();
thread->start();
}
void MyTcpServer::sockDisConnectSlot(int handle, QString ip, quint16 prot)
{
mutex.lock();
MyTcpSocket *tcp = tcpClient.value(handle);
tcpClient.remove(handle);
mutex.unlock();
tcp->deleteLater();
emit sockDisConnect(handle, ip, prot);
}
```
阅读全文