14 网络编程

14 网络编程

主机信息查询

1
2
3
4
5
6
7
8
9
10
11
12
QT += network
#include <QHostInfo>
#include <QNetworkInterface>
QList<QHostAddress> addList=host.addresses();//查找主机信息
aHost.protocol();//协议
QHostInfo::localHostName();//本地主机名
QHostInfo hostInfo=QHostInfo::fromName(hostName); //本机IP地址

QHostInfo::lookupHost(hostname,this,SLOT(lookedUpHostInfo(QHostInfo)));//异步方式查找主机ip

QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();
QList<QNetworkAddressEntry> entryList=aInterface.addressEntries();

TCP通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Server
#include <QtNetwork>//网络相关都包含
QTcpServer *tcpServer=new QTcpServer(this); //TCP服务器
QString IP=ui->comboIP->currentText();//IP地址
quint16 port=ui->spinPort->value();//端口
tcpServer->listen(addr,port);
QTcpSocket *tcpSocket=tcpServer->nextPendingConnection();//TCP通讯的Socket
//发送一行字符串,以换行符结束
QString msg=ui->editMsg->text();
QByteArray str=msg.toUtf8();
str.append('\n');//添加一个换行符
tcpSocket->write(str);

//读取缓冲区行文本
while(tcpSocket->canReadLine())
ui->plainTextEdit->appendPlainText(+tcpSocket->readLine());
if (tcpServer->isListening()) //tcpServer正在监听
{
tcpServer->close();//停止监听
}
//客户端断开连接时
tcpSocket->deleteLater();
tcpServer->close();;//停止网络监听
1
2
3
4
5
6
//Client
QTcpSocket* tcpClient=new QTcpSocket(this); //创建socket变量
QString addr=ui->comboServer->currentText();
quint16 port=ui->spinPort->value();
tcpClient->connectToHost(addr,port);
tcpClient->disconnectFromHost();

UDP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include    <QUdpSocket>
QUdpSocket *udpSocket=new QUdpSocket(this);
udpSocket->bind(port)//绑定端口

//读取收到的数据报
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress peerAddr;
quint16 peerPort;
udpSocket->readDatagram(datagram.data(),datagram.size(),&peerAddr,&peerPort);
QString str=datagram.data();
}

QString msg=ui->editMsg->text();//发送的消息内容
QByteArray str=msg.toUtf8();
udpSocket->writeDatagram(str,targetAddr,targetPort); //发出数据报 向指定的端口和IP

udpSocket->writeDatagram(str,QHostAddress::Broadcast,targetPort);//广播
udpSocket->abort();//断开连接和重置socket

组播

1
2
3
4
5
6
7
8
9
10
QUdpSocket  *udpSocket=new QUdpSocket(this);
QHostAddress groupAddress=QHostAddress(IP);//组播地址
udpSocket>setSocketOption(QAbstractSocket::MulticastTtlOption,1);//Multicast路由层次,1表示只在同一局域网内
if (udpSocket->bind(QHostAddress::AnyIPv4, groupPort, QUdpSocket::ShareAddress))//先绑定端口
{
udpSocket->joinMulticastGroup(groupAddress); //加入多播组
}
//退出组播
udpSocket->leaveMulticastGroup(groupAddress);//退出组播
udpSocket->abort(); //解除绑定

HTTP

1
2
3
4
5
6
7
8
9
#include    <QDesktopServices> //直接打开文件使用
#include <QtNetwork>

QUrl newUrl = QUrl::fromUserInput(urlSpec);//URL地址

QNetworkAccessManager networkManager;//网络管理
QNetworkReply *reply = networkManager.get(QNetworkRequest(newUrl)); //网络响应
reply->readAll();
reply->deleteLater();
作者

步步为营

发布于

2024-05-08

更新于

2025-03-15

许可协议