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

相关推荐
ha20428941943 分钟前
Linux操作系统学习记录之----自定义协议(网络计算器)
linux·网络·学习
java_logo10 分钟前
QWEN3 企业级 Docker 容器化部署指南
运维·docker·容器·qwen3部署·qwen3部署文档·qwen3部署教程·qwen3部署方案
糖~醋排骨11 分钟前
DHCP服务的搭建
linux·服务器·网络
huohaiyu17 分钟前
网络中的一些基本概念
运维·服务器·网络
Kiyra17 分钟前
虚拟机假死?SSH 能连却卡 Logo 界面
运维·ssh
llddycidy24 分钟前
峰值需求预测中的机器学习:基础、趋势和见解(最新文献)
网络·人工智能·深度学习
小林一直冲30 分钟前
华为设备配置与命令
网络
dust_and_stars31 分钟前
ubuntu24使用apt安装VS-code-server code-server
linux·服务器·windows
QH139292318801 小时前
罗德与施瓦茨 与ZNA43网络分析仪的联合测试流程
网络
晚风(●•σ )1 小时前
【华为 ICT & HCIA & eNSP 习题汇总】——题目集28
网络·计算机网络·华为·路由器·ensp·交换机