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

相关推荐
阿赭ochre5 分钟前
Linux环境变量&&进程地址空间
linux·服务器
honey ball6 分钟前
仪表放大器AD620
运维·单片机·嵌入式硬件·物联网·学习
秋已杰爱8 分钟前
进程间关系与进程守护
运维·服务器
微尘88 分钟前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
可儿·四系桜21 分钟前
如何在多台Linux虚拟机上安装和配置Zookeeper集群
linux·服务器·zookeeper
Flying_Fish_roe25 分钟前
linux-软件包管理-包管理工具(Debian 系)
linux·运维·debian
BLEACH-heiqiyihu1 小时前
红帽9中nginx-源码编译php
运维·nginx·php
666786661 小时前
Mysql高级篇(中)—— SQL优化
linux·运维·服务器·数据库·sql·mysql
企业管理8MSaaS1 小时前
了解CRM销售自动化:类型、优势、策略和工具
运维·自动化
pemper_1 小时前
怎么操作使http变成https访问?
网络·网络协议·http·https·ssl