日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

5.关于QT中的网络编程,QTcpSocket,QUdpSocket

發布時間:2024/9/27 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 5.关于QT中的网络编程,QTcpSocket,QUdpSocket 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


1 新建一個項目:TCPServer.pro

A? 修改TCPServer.pro,注意:如果是想使用網絡庫,需要加上network

SOURCES += \

??? TcpServer.cpp \

??? TcpClient.cpp

?

HEADERS += \

??? TcpServer.h \

??? TcpClient.h

?

QT += gui widgets network

?

CONFIG += C++11

B 新建如下文件,因為要用到網絡庫,所以加上network

C 編寫IP選擇下拉選,頭文件ChooseInterface.h

#ifndef CHOOSEINTERFACE_H

#define CHOOSEINTERFACE_H

?

#include <QDialog>

#include <QComboBox>

?

class ChooseInterface : public QDialog

{

??? Q_OBJECT

public:

??? explicit ChooseInterface(QWidget *parent = 0);

??? QComboBox* _comboBox;

?? ?QString _strSelect;

?

signals:

?

public slots:

??? void slotComboBoxChange(QString);

};

?

#endif // CHOOSEINTERFACE_H

編寫ChooseInterface.cpp

#include "ChooseInterface.h"

#include <QNetworkInterface>

#include <QVBoxLayout>

?

ChooseInterface::ChooseInterface(QWidget *parent) :

??? QDialog(parent)

{

??? /* get all interface */

??? QList<QHostAddress> addrList = QNetworkInterface::allAddresses();

#if 0

??? QList<QNetworkInterface> infList = QNetworkInterface::allInterfaces();

?

??? QList<QNetworkAddressEntry> entryList = infList.at(0).addressEntries();

??? entryList.at(0).broadcast()

#endif

?

??? //編寫一個下拉選

??? _comboBox = new QComboBox;

??? QVBoxLayout* lay = new QVBoxLayout(this);

??? lay->addWidget(_comboBox);

?

??? foreach(QHostAddress addr, addrList)

??? {

??????? //將地址都轉換成為ipv4的地址

??????? quint32 ipaddr = addr.toIPv4Address();

??????? //去掉0ip

??????? if(ipaddr == 0)

??????????? continue;

??????? //comboBox中添加下拉選

??????? _comboBox->addItem(QHostAddress(ipaddr).toString());

??? }

?

??? //當下拉選發生變化時的操作

??? connect(_comboBox, SIGNAL(currentIndexChanged(QString)),

??????????? this, SLOT(slotComboBoxChange(QString)));

}

?

void ChooseInterface::slotComboBoxChange(QString str)

{

??? this->_strSelect = str;

}

上面的運行結果是:

編寫TcpServer.h

#ifndef TCPSERVER_H

#define TCPSERVER_H

?

#include <QWidget>

#include <QTcpServer>

#include <QTcpSocket>

#include <QTextBrowser>

?

class TcpServer:public QWidget

{

??? Q_OBJECT

public:

??? explicit TcpServer(QWidget *parent = 0);

?

??? QTcpServer* _server;

??? QTcpSocket* _socket;

?

??? QTextBrowser* _show;

?

signals:

?

public slots:

??? void slotNetConnection();

??? void slotReadyRead();

};

?

#endif // TCPSERVER_H

編寫TcpServer.cpp

#include "TcpServer.h"

#include <QHBoxLayout>

#include <QNetworkInterface>

#include <QMessageBox>

#include "ChooseInterface.h"

?

TcpServer::TcpServer(QWidget *parent) :

??? QWidget(parent)

{

??? // 創建服務器并監聽

??? _server = new QTcpServer;

?

? ??ChooseInterface dlg;

??? dlg.exec();

?

??? //消息提示框

??? QMessageBox::information(NULL,"you select the ip:", dlg._strSelect);

?

??? _server->listen(QHostAddress(dlg._strSelect), 9988);

?

??? // 當有客戶端來連接時,調用slotNetConnection方法

??? connect(_server, SIGNAL(newConnection()),

??????????? this, SLOT(slotNetConnection()));

?

??? _show = new QTextBrowser;

??? QHBoxLayout* lay = new QHBoxLayout(this);

??? lay->addWidget(_show);

}

?

void TcpServer::slotNetConnection()

{

??? // 判斷是否有未處理的連接

??? while(_server->hasPendingConnections())

??? {

??????? // 調用nextPeddingConnection去獲得連接的socket

??????? _socket = _server->nextPendingConnection();

?

??????? _show->append("New connection ....");

?

??????? // 為新的socket提供槽函數,來接收數據

??????? connect(_socket, SIGNAL(readyRead()),

????????????? ??this, SLOT(slotReadyRead()));

??? }

}

?

void TcpServer::slotReadyRead()

{

??? // 接收數據,判斷是否有數據,如果有,通過readAll函數獲取所有數據

??? while(_socket->bytesAvailable() > 0)

??? {

??????? _show->append("Data arrived ..... ");

??????? QByteArray buf = _socket->readAll();

??????? _show->append(buf);

??? }

}

編寫TcpClient.h

#ifndef TCPCLIENT_H

#define TCPCLIENT_H

?

#include <QWidget>

#include <QTcpSocket>

#include <QLineEdit>

?

class TcpClient:public QWidget

{

??? Q_OBJECT

public:

??? explicit TcpClient(QWidget *parent = 0);

? ??QTcpSocket* _socket;

??? QLineEdit* _lineEdit;

?

signals:

?

public slots:

??? void slotButtonClick();

};

?

#endif // TCPCLIENT_H

編寫TcpClient.cpp

#include "TcpClient.h"

#include <QHBoxLayout>

#include <QPushButton>

?

TcpClient::TcpClient(QWidget *parent):

??? QWidget(parent)

{

??? _socket = new QTcpSocket(this);

??? _socket->connectToHost("127.0.0.1", 9988);

?

??? _lineEdit = new QLineEdit;

??? QHBoxLayout* lay = new QHBoxLayout(this);

??? lay->addWidget(_lineEdit);

??? QPushButton* button = new QPushButton("Send");

?

??? lay->addWidget(button);

??? connect(button, SIGNAL(clicked()), this, SLOT(slotButtonClick()));

?

??? connect(_lineEdit, SIGNAL(returnPressed()), this, SLOT(slotButtonClick()));

}

?

void TcpClient::slotButtonClick()

{

??? QString strText = _lineEdit->text();

??? if(strText.isEmpty())

??????? return;

?

??? _socket->write(strText.toUtf8());

??? _lineEdit->clear();

}

MyWidget.h

#ifndef MYWIDGET_H

#define MYWIDGET_H

?

#include <QWidget>

?

class MyWidget : public QWidget

{

??? Q_OBJECT

public:

??? explicit MyWidget(QWidget *parent = 0);

?

signals:

?

public slots:

?

};

?

#endif // MYWIDGET_H

MyWidget.cpp

#include "MyWidget.h"

#include <QApplication>

#include "TcpServer.h"

#include "TcpClient.h"

?

MyWidget::MyWidget(QWidget *parent) :

??? QWidget(parent)

{

}

?

int main(int argc,char** argv)

{

??? QApplication app(argc,argv);

?

??? TcpServer s; s.show();

??? TcpClient c; c.show();

?

??? s.setWindowTitle("server");

??? c.setWindowTitle("client");

?

??? return app.exec();

}

運行結果:

2? 編寫UDP程序

UDPServer.pro

QT += gui widgets network

?

CONFIG += C++11

?

HEADERS += \

??? Udp1.h \

??? Udp2.h \

??? MyWidget.h

?

SOURCES += \

??? Udp1.cpp \

??? Udp2.cpp \

??? MyWidget.cpp

Udp1.h

#ifndef UDP1_H

#define UDP1_H

?

#include <QWidget>

#include <QUdpSocket>

?

class Udp1 : public QWidget

{

??? Q_OBJECT

public:

??? explicit Udp1(QWidget *parent = 0);

??? QUdpSocket* _udp;

?

signals:

?

public slots:

??? void slotReadyRead();

};

?

#endif // UDP1_H

Udp1.cpp

#include "udp1.h"

#include <QTimer>

#include <QDateTime>

Udp1::Udp1(QWidget *parent) :

??? QWidget(parent)

{

? ??// 創建udpsocket,并連接槽函數,用來接收數據

??? _udp = new QUdpSocket;

??? _udp->bind(10001);

??? connect(_udp, SIGNAL(readyRead()),

??????????? this, SLOT(slotReadyRead()));

?

??? // 使用定時器來定時發送時間戳

??? QTimer* timer = new QTimer;

??? timer->setInterval(1000);

??? timer->start();

??? connect(timer, &QTimer::timeout, [&](){

??????? quint64 timestamp = QDateTime::currentMSecsSinceEpoch();

??????? QString str = QString::number(timestamp);

#if 0

??????? // 普通UDPsocket發送

??????? _udp->writeDatagram(str.toUtf8(), QHostAddress("127.0.0.1"), 10002);

#else

??????? // 廣播發送,注意:QHostAddress::Broadcast255.255.255.255, 192.168.6.255

???? //?? _udp->writeDatagram(str.toUtf8(), QHostAddress::Broadcast, 10002);

?

??????? // multicast, 224.0.0.1~224.0.0.255 is multicast address of LAN

?? ?????_udp->writeDatagram(str.toUtf8(), QHostAddress("224.0.0.131"), 10002);

#endif

??? });

}

?

void Udp1::slotReadyRead()

{

??? while(_udp->hasPendingDatagrams())

??? {

??????? quint32 datagramSize = _udp->pendingDatagramSize();

??????? QByteArray buf(datagramSize, 0);

??????? _udp->readDatagram(buf.data(), buf.size());

??????? qDebug() <<"Udp1"<< buf;

??? }

}

Udp2.h

#ifndef UDP2_H

#define UDP2_H

?

#include <QWidget>

#include <QUdpSocket>

class Udp2 : public QWidget

{

??? Q_OBJECT

public:

??? explicit Udp2(QWidget *parent = 0);

??? QUdpSocket* _udp;

?

signals:

?

public slots:

??? void slotReadyRead();

?

};

?

#endif // UDP2_H

Udp2.cpp

#include "udp2.h"

#include <QTimer>

#include <QDateTime>

?

#include <QLineEdit>

?

Udp2::Udp2(QWidget *parent) :

??? QWidget(parent)

{

??? _udp = new QUdpSocket;

?

??? // the address of bind and multicast must be same tpye(IPV4 or IPV6)

??? _udp->bind(QHostAddress::AnyIPv4, 10002);

?

??? // join the multicast address (224.0.0.131) for recv mulicast package

??? _udp->joinMulticastGroup(QHostAddress("224.0.0.131"));

?

??? connect(_udp, SIGNAL(readyRead()),

??????????? this, SLOT(slotReadyRead()));

?

??? QTimer* timer = new QTimer(this);

??? timer->setInterval(1000);

??? timer->start();

??? connect(timer, &QTimer::timeout, [&](){

??????? quint64 timestamp = QDateTime::currentMSecsSinceEpoch();

??????? QString str = QString::number(timestamp);

??????? _udp->writeDatagram(str.toUtf8(), QHostAddress("127.0.0.1"), 10001);

??? });

}

?

void Udp2::slotReadyRead()

{

??? while(_udp->hasPendingDatagrams())

??? {

??????? quint32 datagramSize = _udp->pendingDatagramSize();

??????? QByteArray buf(datagramSize, 0);

??????? _udp->readDatagram(buf.data(), buf.size());

??????? qDebug() << "Udp2" <<buf;

??? }

}

運行結果:

控制臺輸出結果如下:

?

總結

以上是生活随笔為你收集整理的5.关于QT中的网络编程,QTcpSocket,QUdpSocket的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。