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

相关推荐
jiayong231 天前
DevOps体系详解01-核心概念与价值
运维·devops
jiayong231 天前
DevOps体系详解02-技术架构与工具链
运维·架构·devops
pride.li1 天前
开发板和Linux--nfs服务挂载
linux·运维·服务器
looking_for__1 天前
【Linux】应用层协议
linux·服务器·网络
云泽8081 天前
不止是命令:Linux 高频指令实战 + 芯片架构底层逻辑
linux·运维·服务器
j_xxx404_1 天前
Linux:基础IO
linux·运维·服务器
以太浮标1 天前
华为eNSP模拟器综合实验之- VLAN终结实践案例分析
网络·计算机网络·华为·智能路由器
angushine1 天前
银河麒麟V10创建用户
运维
Trouvaille ~1 天前
【Linux】网络编程基础(二):数据封装与网络传输流程
linux·运维·服务器·网络·c++·tcp/ip·通信
柱子jason1 天前
使用IOT-Tree Server模拟Modbus设备对接西门子PLC S7-200
网络·物联网·自动化·modbus·西门子plc·iot-tree·协议转换