1,獲取本機網絡信息
獲取主機信息
QString hostname = QHostInfo::localHostName();
qDebug() << hostname; QHostInfo hostinfo = QHostInfo::fromName(hostname); QList<QHostAddress>listaddr = hostinfo.addresses();
for (int i=0; i<listaddr.size();i++)
{
qDebug() << listaddr.at(i);
}
2,獲得與網絡接口相關信息
QList<QNetworkInterface>list = QNetworkInterface::allInterfaces();for (int i=0; i<list.count(); i++)
{
QNetworkInterface face = list.at(i);QList<QNetworkAddressEntry>entrylist = face.addressEntries();
for (int j=0; j<entrylist.count(); j++)
{
QNetworkAddressEntry entry = entrylist.at(j);
qDebug() << "ip:" << entry.ip();
}
}
3,基於UDP網絡編程
服務器端
創建套接字
serverSocket = new udpsocket(this);
綁定套接字
serverSocket->bind(QHostAddress::Any, 8040);
設定當有數據可以接收調用的槽函數
connect(this, SIGNAL(readyRead()), this, SLOT(recvdata()));
數據接收槽函數實現
protected slots:
void recvdata()
{
while (this->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(this->pendingDatagramSize());
this->readDatagram(datagram.data(), datagram.size());QString s = datagram.data();
QMessageBox::information(NULL, "msg", s);;
emit updatemsg(s);
}
}
客戶端
創建套接字
QUdpSocket *socket = new QUdpSocket(this);
發送數據
QString s = “hello";
socket->writeDatagram(s.toLatin1(), s.length(), QHostAddress::Broadcast, 8040);
4,基於TCP網絡編程
服務器端
QTcpSever創建監聽套接字
tcpServer::tcpServer(QObject *parent, int port): QTcpServer(parent)
{
listen(QHostAddress::Any, port);
}
重寫QTcpSever ::incomingConnection(int)方法,該函數當有新的連接時會被自動調用
void tcpServer::incomingConnection(int sock)
{
tcpSocket *tcpsock = new tcpSocket(this);
tcpsock->setSocketDescriptor(sock);
}
創建QTcpSocket連接套接字
tcpSocket::tcpSocket(QObject *parent): QTcpSocket(parent) {
connect(this, SIGNAL(readyRead()), this, SLOT(dataRecv()));
}
void tcpSocket::dataRecv()
{ while (bytesAvailable() > 0) {
int len = bytesAvailable();
char buf[1024] = {0};
read(buf, len);
QMessageBox::information(NULL, "msg", buf);
}
}
QIODevice是所有Qt I/O設備的基類, readyRead() -- 當data有新數據準備好時發出信號。例如,新數據通過network到達或者有數據附加到了你正在讀取的文件之後;
bytesAvailable()-- 確定當前可讀數據的字節數,當對非同步設備例如QTcpSocket(此類設備的數據段到達的時間是隨機的)編程時,常與readyRead()信號聯用。
客戶端
創建套接字
QTcpSocket *socket = new QTcpSocket(this);
連接服務器
socket->connectToHost(QHostAddress("127.0.0.1"), 8010);
發送消息
QString s = "hello server";
socket->write(s.toLatin1(), s.length());
博文索引 持續更新中。。。