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

相关推荐
Menior_14 分钟前
[Linux] vim及gcc工具
linux·运维·vim
----云烟----28 分钟前
使用libUSB-win32的简单读写例程参考
网络
weixin_4738947736 分钟前
前端服务器部署分类总结
前端·网络·性能优化
不念霉运40 分钟前
2025年中国DevOps工具选型指南:主流平台能力横向对比
运维·ci/cd·团队开发·devops
HelloZheQ41 分钟前
MVCC:数据库并发控制的利器
服务器·数据库·oracle
珹洺1 小时前
Jsp技术入门指南【十四】实现基于MySQL+JDBC+JSP数据库验证的登录界面与登录跳转功能
java·运维·数据库·mysql·servlet
OpenVINO生态社区1 小时前
【美国将取消对能源之星支持 严重影响AI服务器】
服务器·人工智能·能源
珹洺1 小时前
计算机操作系统(七)详细讲解进程的组成与特性,状态与转换
运维·服务器·计算机网络
上海云盾-高防顾问1 小时前
SCDN如何有效防护网站免受CC攻击?——安全加速网络的实战解析
网络·安全
alden_ygq1 小时前
nginx 出现大量connect reset by peer
服务器·网络·nginx