qt多线程tcp服务器
时间: 2023-08-10 09:05:56 浏览: 203
实现一个多线程TCP服务器,可以使用Qt的网络模块和多线程模块。
以下是一个简单的示例代码:
```c++
#include <QtNetwork>
#include <QtCore>
class TcpServer : public QObject
{
Q_OBJECT
public:
TcpServer(QObject *parent = nullptr) : QObject(parent) {
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
}
void listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0) {
server->listen(address, port);
}
private slots:
void newConnection() {
QTcpSocket *socket = server->nextPendingConnection();
if (socket) {
QThread *thread = new QThread(this);
TcpSocketWorker *worker = new TcpSocketWorker(socket);
worker->moveToThread(thread);
connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(worker, SIGNAL(error(QString)), this, SLOT(socketError(QString)));
thread->start();
}
}
void socketError(const QString &errorString) {
qDebug() << errorString;
}
private:
QTcpServer *server;
};
class TcpSocketWorker : public QObject
{
Q_OBJECT
public:
TcpSocketWorker(QTcpSocket *socket, QObject *parent = nullptr) : QObject(parent), socket(socket) {
connect(socket, SIGNAL(readyRead()), this, SLOT(read()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));
}
public slots:
void process() {
qDebug() << "New connection from" << socket->peerAddress().toString() << ":" << socket->peerPort();
// Process the data here
}
void read() {
QByteArray data = socket->readAll();
// Process the data here
}
void disconnected() {
qDebug() << "Connection closed by" << socket->peerAddress().toString() << ":" << socket->peerPort();
emit finished();
}
void error(QAbstractSocket::SocketError error) {
QString errorString = socket->errorString();
qDebug() << "Socket error:" << errorString;
emit error(errorString);
}
signals:
void finished();
void error(const QString &errorString);
private:
QTcpSocket *socket;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TcpServer server;
server.listen(QHostAddress::Any, 1234);
return a.exec();
}
#include "main.moc"
```
这个示例代码中,TcpServer类作为服务器端的入口点,监听来自客户端的连接请求。一旦收到连接请求,TcpServer会在一个新的线程中为该客户端创建一个TcpSocketWorker对象,并将QTcpSocket对象移动到该线程中进行处理。
TcpSocketWorker类是一个QObject类,它处理来自客户端的数据和连接状态变化。在process()槽函数中,可以处理来自客户端的数据。在read()槽函数中,可以读取来自客户端的数据。在disconnected()槽函数中,可以处理连接关闭事件。在error()槽函数中,可以处理socket错误事件。
注意:在处理来自客户端的数据时,可能需要使用线程安全的数据结构和算法来保证线程安全。
阅读全文