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进行通信。

相关推荐
en.en..1 小时前
Linux系统编程:fcntl 与 ioctl
linux·运维·服务器
CLK音视频广播设备2 小时前
河南川利卡科技集团圆满落地安徽宿州校园网络广播项目
网络·科技
荣合技术服务2 小时前
Codex 实战:用 AI 写运维脚本
运维·codex
会周易的程序员2 小时前
5Draft(五帝)测试报告
服务器·c++·分布式·raft·共识算法·共识·算力服务器
李昊哲小课2 小时前
Deepin 25 上安装 Docker CE 实战记录
运维·docker·容器·deepin
pingglala2 小时前
ubuntu-nat模式不能上网解决方法
linux·运维·ubuntu
一技安身2 小时前
【信创】外网aarch64终端安装deepseek Ragflow 迁移至内网银河麒麟服务器
运维·服务器
M哥支付3 小时前
快捷支付 VS 网关支付 安全对比
服务器·网络·其他·微信·金融
考虑考虑3 小时前
ElasticSearch索引命令
运维·后端·elasticsearch
2501_928996223 小时前
Agent 开发的 API 选型:从 Function Calling 到多模型协作的中科热备底层逻辑
服务器·重构·gitlab