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

时间:2022-10-08 05:28:54


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

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

C编写IP选择下拉选,头文件ChooseInterface.h

#ifndefCHOOSEINTERFACE_H

#defineCHOOSEINTERFACE_H

 

#include<QDialog>

#include<QComboBox>

 

classChooseInterface:publicQDialog

{

   Q_OBJECT

public:

   explicitChooseInterface(QWidget*parent= 0);

   QComboBox*_comboBox;

   QString_strSelect;

 

signals:

 

publicslots:

   voidslotComboBoxChange(QString);

};

 

#endif//CHOOSEINTERFACE_H

编写ChooseInterface.cpp

#include"ChooseInterface.h"

#include<QNetworkInterface>

#include<QVBoxLayout>

 

ChooseInterface::ChooseInterface(QWidget*parent):

   QDialog(parent)

{

   /*getallinterface*/

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

#if0

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

 

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

   entryList.at(0).broadcast()

#endif

 

   //编写一个下拉选

   _comboBox=newQComboBox;

   QVBoxLayout*lay=newQVBoxLayout(this);

   lay->addWidget(_comboBox);

 

   foreach(QHostAddressaddr,addrList)

   {

       //将地址都转换成为ipv4的地址

       quint32ipaddr=addr.toIPv4Address();

       //去掉0ip

       if(ipaddr==0)

           continue;

       //comboBox中添加下拉选

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

   }

 

   //当下拉选发生变化时的操作

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

           this,SLOT(slotComboBoxChange(QString)));

}

 

voidChooseInterface::slotComboBoxChange(QStringstr)

{

   this->_strSelect=str;

}

上面的运行结果是:

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

编写TcpServer.h

#ifndefTCPSERVER_H

#defineTCPSERVER_H

 

#include<QWidget>

#include<QTcpServer>

#include<QTcpSocket>

#include<QTextBrowser>

 

classTcpServer:publicQWidget

{

   Q_OBJECT

public:

   explicitTcpServer(QWidget*parent= 0);

 

   QTcpServer*_server;

   QTcpSocket*_socket;

 

   QTextBrowser*_show;

 

signals:

 

publicslots:

   voidslotNetConnection();

   voidslotReadyRead();

};

 

#endif//TCPSERVER_H

编写TcpServer.cpp

#include"TcpServer.h"

#include<QHBoxLayout>

#include<QNetworkInterface>

#include<QMessageBox>

#include"ChooseInterface.h"

 

TcpServer::TcpServer(QWidget*parent):

   QWidget(parent)

{

   //创建服务器并监听

   _server=newQTcpServer;

 

   ChooseInterfacedlg;

   dlg.exec();

 

   //消息提示框

   QMessageBox::information(NULL,"youselecttheip:",dlg._strSelect);

 

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

 

   //当有客户端来连接时,调用slotNetConnection方法

   connect(_server,SIGNAL(newConnection()),

           this,SLOT(slotNetConnection()));

 

   _show=newQTextBrowser;

   QHBoxLayout*lay=newQHBoxLayout(this);

   lay->addWidget(_show);

}

 

voidTcpServer::slotNetConnection()

{

   //判断是否有未处理的连接

   while(_server->hasPendingConnections())

   {

       //调用nextPeddingConnection去获得连接的socket

       _socket=_server->nextPendingConnection();

 

       _show->append("Newconnection....");

 

       //为新的socket提供槽函数,来接收数据

       connect(_socket,SIGNAL(readyRead()),

               this,SLOT(slotReadyRead()));

   }

}

 

voidTcpServer::slotReadyRead()

{

   //接收数据,判断是否有数据,如果有,通过readAll函数获取所有数据

   while(_socket->bytesAvailable()>0)

   {

       _show->append("Dataarrived.....");

       QByteArraybuf=_socket->readAll();

       _show->append(buf);

   }

}

编写TcpClient.h

#ifndefTCPCLIENT_H

#defineTCPCLIENT_H

 

#include<QWidget>

#include<QTcpSocket>

#include<QLineEdit>

 

classTcpClient:publicQWidget

{

   Q_OBJECT

public:

   explicitTcpClient(QWidget*parent= 0);

   QTcpSocket*_socket;

   QLineEdit*_lineEdit;

 

signals:

 

publicslots:

   voidslotButtonClick();

};

 

#endif//TCPCLIENT_H

编写TcpClient.cpp

#include"TcpClient.h"

#include<QHBoxLayout>

#include<QPushButton>

 

TcpClient::TcpClient(QWidget*parent):

   QWidget(parent)

{

   _socket=newQTcpSocket(this);

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

 

   _lineEdit=newQLineEdit;

   QHBoxLayout*lay=newQHBoxLayout(this);

   lay->addWidget(_lineEdit);

   QPushButton*button=newQPushButton("Send");

 

   lay->addWidget(button);

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

 

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

}

 

voidTcpClient::slotButtonClick()

{

   QStringstrText=_lineEdit->text();

   if(strText.isEmpty())

       return;

 

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

   _lineEdit->clear();

}

MyWidget.h

#ifndefMYWIDGET_H

#defineMYWIDGET_H

 

#include<QWidget>

 

classMyWidget:publicQWidget

{

   Q_OBJECT

public:

   explicitMyWidget(QWidget*parent= 0);

 

signals:

 

publicslots:

 

};

 

#endif//MYWIDGET_H

MyWidget.cpp

#include"MyWidget.h"

#include<QApplication>

#include"TcpServer.h"

#include"TcpClient.h"

 

MyWidget::MyWidget(QWidget*parent):

   QWidget(parent)

{

}

 

intmain(intargc,char**argv)

{

   QApplicationapp(argc,argv);

 

   TcpServers;s.show();

   TcpClientc;c.show();

 

   s.setWindowTitle("server");

   c.setWindowTitle("client");

 

   returnapp.exec();

}

运行结果:

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

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

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

#ifndefUDP1_H

#defineUDP1_H

 

#include<QWidget>

#include<QUdpSocket>

 

classUdp1:publicQWidget

{

   Q_OBJECT

public:

   explicitUdp1(QWidget*parent= 0);

   QUdpSocket*_udp;

 

signals:

 

publicslots:

   voidslotReadyRead();

};

 

#endif//UDP1_H

Udp1.cpp

#include"udp1.h"

#include<QTimer>

#include<QDateTime>

Udp1::Udp1(QWidget*parent):

   QWidget(parent)

{

   //创建udpsocket,并连接槽函数,用来接收数据

   _udp=newQUdpSocket;

   _udp->bind(10001);

   connect(_udp,SIGNAL(readyRead()),

           this,SLOT(slotReadyRead()));

 

   //使用定时器来定时发送时间戳

   QTimer*timer=newQTimer;

   timer->setInterval(1000);

   timer->start();

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

       quint64timestamp=QDateTime::currentMSecsSinceEpoch();

       QStringstr=QString::number(timestamp);

#if0

       //普通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.255ismulticastaddressofLAN

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

#endif

   });

}

 

voidUdp1::slotReadyRead()

{

   while(_udp->hasPendingDatagrams())

   {

       quint32datagramSize=_udp->pendingDatagramSize();

       QByteArraybuf(datagramSize,0);

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

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

   }

}

Udp2.h

#ifndefUDP2_H

#defineUDP2_H

 

#include<QWidget>

#include<QUdpSocket>

classUdp2:publicQWidget

{

   Q_OBJECT

public:

   explicitUdp2(QWidget*parent= 0);

   QUdpSocket*_udp;

 

signals:

 

publicslots:

   voidslotReadyRead();

 

};

 

#endif//UDP2_H

Udp2.cpp

#include"udp2.h"

#include<QTimer>

#include<QDateTime>

 

#include<QLineEdit>

 

Udp2::Udp2(QWidget*parent):

   QWidget(parent)

{

   _udp=newQUdpSocket;

 

   //theaddressofbindandmulticastmustbesametpye(IPV4orIPV6)

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

 

   //jointhemulticastaddress(224.0.0.131)forrecvmulicastpackage

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

 

   connect(_udp,SIGNAL(readyRead()),

           this,SLOT(slotReadyRead()));

 

   QTimer*timer=newQTimer(this);

   timer->setInterval(1000);

   timer->start();

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

       quint64timestamp=QDateTime::currentMSecsSinceEpoch();

       QStringstr=QString::number(timestamp);

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

   });

}

 

voidUdp2::slotReadyRead()

{

   while(_udp->hasPendingDatagrams())

   {

       quint32datagramSize=_udp->pendingDatagramSize();

       QByteArraybuf(datagramSize,0);

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

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

   }

}

运行结果:

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

控制台输出结果如下:

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