A UDP introduction
UDP is a simple, lightweight transport layer protocol that provides non-connected, unreliable message transmissions. Suitable for the following 4 situations:
Most of the network data is short messages.
Has a large number of clients.
No special requirements for data security
The network burden is very heavy, but the response speed requirements are high.
Two-c/s programming model based on UDP protocol (broadcast), multicast words, see tomorrow.
Client:
classSender: Publicqobject{Q_object//signals and slots can be used Public: ExplicitSender (Qobject *parent =0); ~sender ();//no return value for imaginary function voidstart (); PublicSlots:voidBroadcastdatagram ();Private: Qudpsocket*udpsocket;//<QtNetwork/qudpsocket.h> includedQtimer *timer; intMessageno;};
Qt +=network is added to Qt's. Pro file when using UDP TCP.
Specific implementation:
#include"Sender.h"Sender::sender (Qobject*parent): Qobject (parent) {Timer=NewQtimer ( This); Udpsocket=NewQudpsocket ( This); Connect (timeout ()), Timer,signal This, SLOT (Broadcastdatagram ())); Messageno=1;}voidSender::start () {Timer->start ( +);}voidSender::broadcastdatagram () {qdebug ()<< (TR ("Begin Broadcast:%1"). Arg (Messageno)); Qbytearray Datagram="Broadcast Message:"+Qbytearray::number (Messageno); Udpsocket->writedatagram (Datagram.data (), Datagram.size (), Qhostaddress::broadcast,44444); ++Messageno;} Sender::~Sender () {Deletetimer; DeleteUdpsocket;//do you want to remove connect? }
Udpsocket->writedatagram (Datagram.data (), Datagram.size (), qhostaddress::broadcast,44444);
Function prototype: Writedatagram (const char* data,qint64 size,const qhostaddress &address,quint16 Port)
function function: Send a packet
Function parameters: The packet itself, the packet size, the address sent to, the port.
Receiving end:
class Public qobject{ q_objectpublic: Explicit0); ~Receiver (); Signals: Public Slots: void Processpendingdatagrams (); Private : *udpsocket;};
Specific implementation:
#include"Receiver.h"Receiver::receiver (Qobject*parent): Qobject (parent) {Udpsocket=NewQudpsocket ( This); Udpsocket->bind (44444); Connect (udpsocket,signal (readyread)), This, SLOT (Processpendingdatagrams ()));}voidReceiver::p rocesspendingdatagrams () { while(udpsocket->Haspendingdatagrams ()) {Qbytearray datagram; Datagram.resize (Udpsocket-pendingdatagramsize ()); Udpsocket-Readdatagram (Datagram.data (), datagram.size ()); Qdebug ()<< (TR ("receice Data: \ "%1\""). Arg (Datagram.data ())); }}receiver::~Receiver () {DeleteUdpsocket;}
When the packet is received, the Qudpsocket emits a readyread () signal. I have associated processpendingdatagrams ().
Use Haspendingdatagrams () first to determine if there is data available for reading. If so, a buffer is opened with pendingdatagramsize ().
Finally, the message is read into the buffer with Readdatagram ().
UDP Multicast technology for QT