tcp服务器端与多个客户端连接

如果希望Tcp服务器端可以与多个客户端连接,可以这样写:

cpp 复制代码
    tcpServer=new QTcpServer(this);
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
cpp 复制代码
void MainWindow::onNewConnection()
{
    QTcpSocket *tcpSocket;//TCP通讯的Socket
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket
    qDebug()<<"tcpSocket:"<<tcpSocket;
    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(onClientConnected()));
    emit tcpSocket->connected();

    connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(onClientDisconnected()));

    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
    emit tcpSocket->stateChanged(tcpSocket->state());

    connect(tcpSocket,SIGNAL(readyRead()),
            this,SLOT(onSocketReadyRead()));
}

相关的槽函数中:

cpp 复制代码
void MainWindow::onClientConnected()
{//客户端接入时
    QTcpSocket* tcpSocket=(QTcpSocket*)sender();
    ui->plainTextEdit->appendPlainText("**client socket connected");
    ui->plainTextEdit->appendPlainText("**peer address:"+
                                   tcpSocket->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**peer port:"+
                                   QString::number(tcpSocket->peerPort()));
}

使用sender()来获取对应的QTcpSocket对象。

其实,主要就是QTcpServer进行监听:

客户端的QTcpSocket与服务器端的QTcpSocket进行通信。

相关推荐
Yana.nice7 小时前
Linux 只保留 30 天内日志(find命令删除日志文件)
linux·运维·chrome
andxe9 小时前
安科士 AndXe 技术博客:400G QSFP112 SR4 光模块|AI 算力与超算短距互联最优方案
网络·人工智能·光模块·光通信
2601_960567969 小时前
电商套图自动化效率的工程量化分析——从逐张生成到批量套图的架构演进
运维·架构·自动化
shiyi.十一10 小时前
第2章:应用层 — 知识要点与架构
网络·计算机网络·架构
吳所畏惧10 小时前
宝塔面板Redis密码修改指南:SSH命令修改 vs 面板UI界面修改,哪个更靠谱?
运维·服务器·数据库·redis·缓存·ssh
DFT计算杂谈10 小时前
无 Root 权限在 Tesla K80 零门槛部署 DeepSeek 大模型
linux·服务器·网络·数据库·机器学习
水境传感 李兆栋10 小时前
GNSS 位移监测站 :毫米级感知,筑牢安全监测防线
网络
HiDev_11 小时前
【非标自动化】2、认识元器件(确定目标)
运维·自动化
维天说11 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
Zhang~Ling11 小时前
从 fopen 到 struct file:从零开始拆解 Linux 文件 I/O
linux·运维·服务器