~本次添加的功能:

根据不同模式采用不同的TCP连接模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if(ui->LinkBotton->property("Mode")=="Server"){   //设置为服务器监听模式
m_tcpServer=new QTcpServer(this);
//服务端监听客户端发来的请求
if(!m_tcpServer->listen(QHostAddress::AnyIPv4,6666)){
qDebug()<<m_tcpServer->errorString();
close();
}
connect(m_tcpServer,&QTcpServer::newConnection,this,&MainWindow::onNewConnect);
connect(m_tcpServer,&QTcpServer::newConnection,this,&MainWindow::onSendBackMsg);
}
else if(ui->LinkBotton->property("Mode")=="Client"){ //设置为客户端模式
m_tcpSocket=new QTcpSocket(this);
//socket有数据来了,做处理
connect(m_tcpSocket,&QTcpSocket::readyRead,
this,&MainWindow::onReadMessage);
connect(m_tcpSocket,SIGNAL(QAbstractSocket::SocketError),
this,SLOT(onDisplayError(QAbstractSocket::SocketError)));
m_tcpSocket->abort();
//连接服务端
m_tcpSocket->connectToHost(ui->Host->text(),
ui->Port->text().toInt());
}

建立新连接:

1
2
3
4
5
6
7
8
9
10
11
void MainWindow::onNewConnect()
{
//当前连接的客户端
m_tcpSocket=m_tcpServer->nextPendingConnection();
//断开连接
connect(m_tcpSocket,&QTcpSocket::disconnected,
m_tcpSocket,&QTcpSocket::deleteLater);
//socket有数据时会发送readyRead信号
connect(m_tcpSocket,&QTcpSocket::readyRead,
this,&MainWindow::onReadMsg);
}

服务器接受数据后处理函数:

1
2
3
4
void MainWindow::onReadMsg()
{
//作为服务器时接收到数据处理信息
}