qt tcp 多个客户端
时间: 2025-06-29 20:03:08 浏览: 2
### 实现QT框架下的TCP多客户端连接
#### 创建TCP服务器类
为了支持多个客户端的同时连接,在创建`QTcpServer`对象时,每当有新的客户端尝试建立连接时,都会触发`newConnection()`信号。此时应该监听这个信号并处理新连接。
```cpp
class MyTcpServer : public QObject {
Q_OBJECT
public:
explicit MyTcpServer(QObject *parent = nullptr);
private slots:
void onNewConnection();
};
MyTcpServer::MyTcpServer(QObject *parent) :
QObject(parent), server(new QTcpServer(this)) {
connect(server, &QTcpServer::newConnection,
this, &MyTcpServer::onNewConnection);
}
```
当接收到新的连接请求时,会调用`onNewConnection()`函数来接受该连接,并为每一个新连接分配一个新的套接字实例[^1]。
```cpp
void MyTcpServer::onNewConnection() {
while (server->hasPendingConnections()) {
QTcpSocket* clientConnection = server->nextPendingConnection();
qDebug() << "New connection from:" << clientConnection->peerAddress().toString();
// 将clientConnection保存起来以便后续管理
clients.append(clientConnection);
// 连接到readyRead信号以读取数据
connect(clientConnection,&QTcpSocket::readyRead,this,[=]() {
QByteArray data = clientConnection->readAll();
qDebug()<<data;
// 广播消息给其他所有已连接的客户端
foreach(QTcpSocket* socket,clients){
if(socket != clientConnection && socket->state()==QAbstractSocket::Connected
阅读全文
相关推荐


















