如果希望Tcp服务器端可以与多个客户端连接,可以这样写:
tcpServer=new QTcpServer(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
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()));
}
相关的槽函数中:
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进行通信。文章来源:https://www.toymoban.com/news/detail-860533.html
文章来源地址https://www.toymoban.com/news/detail-860533.html
到了这里,关于tcp服务器端与多个客户端连接的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!