如果希望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进行通信。