linux QT tcpserver代码
时间: 2025-05-17 16:13:16 浏览: 24
### QT TCP Server 实现代码示例
以下是基于QT框架在Linux环境下实现的一个简单的TCP服务器的代码示例。此代码展示了如何创建并监听端口,以及处理客户端连接。
#### 主窗口类定义
```cpp
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
class TcpServer : public QObject {
Q_OBJECT
public:
explicit TcpServer(QObject *parent = nullptr);
private slots:
void newConnection();
void readClient();
private:
QTcpServer *server;
};
```
#### 构造函数与槽函数实现
```cpp
TcpServer::TcpServer(QObject *parent) :
QObject(parent), server(new QTcpServer(this)) {
if (!server->listen(QHostAddress::Any, 12345)) { // 绑定到任意地址上的12345端口
qDebug() << "Server could not start!";
} else {
qDebug() << "Server started!";
connect(server, &QTcpServer::newConnection, this, &TcpServer::newConnection);
}
}
void TcpServer::newConnection() {
QTcpSocket *clientConnection = server->nextPendingConnection(); // 获取新连接
clientConnection->write("Hello Client!\n");
clientConnection->flush();
clientConnection->waitForBytesWritten(1000); // 等待数据写入完成
connect(clientConnection, &QTcpSocket::readyRead, this, &TcpServer::readClient);
}
void TcpServer::readClient() {
QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
if (client) {
QString data = client->readAll(); // 读取来自客户端的数据
qDebug() << "Data from client:" << data;
}
}
```
#### 主程序入口
```cpp
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
TcpServer server;
return app.exec();
}
```
上述代码实现了基本的TCP服务器功能[^1]。它通过`QTcpServer`对象绑定到指定端口上,并等待客户端发起连接请求。当有新的客户端连接时,会触发`newConnection()`信号;而每当接收到客户端发来的消息时,则会调用`readClient()`方法进行响应。
对于更复杂的场景,可以扩展此类逻辑以支持多线程操作或者异步通信模式[^2]。
---
###
阅读全文
相关推荐
















