0%

Qt网络编程

Qt网络编程

服务端

获取IP

getLocalHostIP()
{
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
foreach (QNetworkInterface interface, list)
{
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
foreach(QNetworkAddressEntry entry ,entryList)
{
if(entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
{
if(entry.ip().toString() == "127.0.0.1")continue;
comboBox->addItem(entry.ip().toString());
IPlist<<entry.ip();
}
}
}
}

allInterfaces()获取本地的所有网络接口,比如wlan,本地连接等等,然后使用addressEntries()获取所有IP地址,使用IPv4Protocol筛选所有的IPv4地址,进行连接,同时在

if(entry.ip().toString() == "127.0.0.1")continue;

中筛选去掉本地IP,只留下有意义的(可以从外部连接的)IP地址。

监听

startListen()
{
if(comboBox->currentIndex() != -1)
{
qDebug()<<"start Listen"<<endl;
tcpServer->listen(IPlist[comboBox->currentIndex()], spinBox->value());
btn1->setEnabled(false);
btn2->setEnabled(true);
comboBox->setEnabled(false);
spinBox->setEnabled(false);
clientBrowser->append("server IP address:"+comboBox->currentText());
clientBrowser->append("Listening port: "+spinBox->text());

}
}

监听就是使用tcpServer对象,监听IP和端口,通过函数传入,等待程序链接

停止监听

stopListen()
{
qDebug()<<"stop listen"<<endl;
tcpServer->close();
if(tcpSocket->state() == tcpSocket->ConnectedState)
{
tcpSocket->disconnectFromHost();
}
btn1->setEnabled(true);
btn2->setEnabled(false);
clientBrowser->append("Stopped Listening: "+spinBox->text());
comboBox->setEnabled(true);
spinBox->setEnabled(true);

}

注意,调用tcpServer->close()之后,已经连接的客户端还可以继续与主机进行通信,此时需要tcpSocket->disconnectFromHost();来断开当前连接的客户端与服务器的链接,**注意此时调用的tcpSocket对象是用户连接时候从下面的tcpServer->nextPendingConnection()获得的Socket对象 **。

应对用户链接

clientConnection()
{
tcpSocket = tcpServer->nextPendingConnection();
QString ip = tcpSocket->peerAddress().toString();
quint16 port = tcpSocket->peerPort();
clientBrowser->append("Client IP: "+ip);
clientBrowser->append("Client port"+QString::number(port));

connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(recMessage()));
}

注意用户链接的时候,可以通过tcpServer->nextPendingConnection();获取用户链接的Socket对象,进而获取tcpSocket->peerAddress().toString();IP和tcpSocket->peerPort();端口号

收取消息

recMessage()
{
QString messages = tcpSocket->readAll();
clientBrowser->append(messages);
qDebug()<<messages<<endl;
}

发送消息

sendMessage()
{
if(tcpSocket->state() == tcpSocket->ConnectedState)
{
tcpSocket->write(send->text().toUtf8().data());
clientBrowser->append("Server:"+send->text());
}
}

客户端

此处仅仅强调客户端与服务器的区别

链接服务器

toConnect()
{
if(tcpSocket->state()!=tcpSocket->ConnectedState)
{
QHostAddress hostAdd;
hostAdd.setAddress(ipInput->text());
textBrowser->append("Connecting: " + hostAdd.toString() + " ...");
tcpSocket->connectToHost(hostAdd, spinBox->value());

}
}
  • 注意QHostAddress具有从字符串0-255点分格式的IP地址中parse出IP地址的功能(hostAdd.setAddress(ipInput->text());)

断开连接

toDisconnect()
{
tcpSocket->disconnectFromHost();
tcpSocket->close();
}

其他与编写服务端类似,在此不再赘述。