Qt进阶-网口通信
获取当前IP
QList<QHostAddress> addressList = QNetworkInterface::allAddresses(); //获取所有的网络列表
QString IP = "";
for each(QHostAddress address in addressList)
{
//获取Ipv4网络,并且非空且不等于127.0.0.1
if (address.protocol() == QAbstractSocket::IPv4Protocol &&address != QHostAddress::Null && address != QHostAddress::LocalHost)
{
IP = address.toString();
ui->lineEdit_socketIP->setText(IP);
break;
}
}
服务端
服务端开启监听
QTcpServer *m_tcpServer = new QTcpServer; //tcp服务端对象
QString serverIP = ui->lineEdit_socketIP->text();
int serverPort = ui->lineEdit_portId->text().toInt();
bool flg = m_tcpServer->listen(QHostAddress(serverIP), serverPort);
新的客户端连接到达
connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(sls_tcpServerNewConnection())); //tcp服务端有新连接到达
void ComNetTool::sls_tcpServerNewConnection()
{
QTcpSocket *newSocket = m_tcpServer->nextPendingConnection();
connect(newSocket, SIGNAL(readyRead()), this, SLOT(sls_tcpServerRecvMsg())); //tcp客户端接收数据
ui->cbBox_socketInfo->addItem(newSocket->peerAddress().toString() + ":" + QString::number(newSocket->peerPort()));
m_clientList.append(newSocket);
}
服务端接收数据
void ComNetTool::sls_tcpServerRecvMsg()
{
QTcpSocket *s = (QTcpSocket *)sender();
QByteArray recvBuffer = s->readAll(); //获取网口数据
if (!recvBuffer.isEmpty())
{
ui->textEdit_recText->append(QString("[网口:从%1:%2接收]\r\n").arg(s->peerAddress().toString()).arg(s->peerPort()) + QString::fromLocal8Bit(recvBuffer)); //显示数据,fromLocal8Bit防止中文乱码
}
}
服务端发送数据
int socketIndex = ui->cbBox_socketInfo->currentIndex();
if (0 == socketIndex) //给所有客户端对象发送
{
for each (QTcpSocket *s in m_clientList)
{
s->write(data);
}
}
else //给单一客户端对象发送
{
m_clientList.at(socketIndex - 1)->write(data);
}
客户端
连接到服务端
QTcpSocket *m_tcpSocket = new QTcpSocket; //tcp客户端对象
QString serverIP = ui->lineEdit_socketIP->text();
int serverPort = ui->lineEdit_portId->text().toInt();
//连接到服务端
m_tcpSocket->abort(); //断开连接
m_tcpSocket->connectToHost(serverIP, serverPort); //连接服务端
bool bRet = m_tcpSocket->waitForConnected(1000);
if (!bRet)
{
//...
}
else
{
ui->cbBox_socketInfo->addItem(m_tcpSocket->localAddress().toString() + ":" + QString::number(m_tcpSocket->localPort())); //当前客户端信息
}
客户端接收数据
connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(sls_tcpSocketRecvMsg())); //tcp客户端接收数据
void ComNetTool::sls_tcpSocketRecvMsg()
{
QByteArray recvBuffer = m_tcpSocket->readAll(); //获取网口数据
if (!recvBuffer.isEmpty())
{
ui->textEdit_recText->append(QString::fromLocal8Bit(recvBuffer)); //显示数据,fromLocal8Bit防止中文乱码
}
}
客户端发送数据
QByteArray sendData = ui->textEdit_send->toPlainText().toLocal8Bit(); //防止中文乱码
m_tcpSocket->write(sendData); //写入网口数据