Get the App
SLTechnology News&Howtos  ›  Network Security  › 

UDP communication code and interpretation of qt

Shulou Source: shulou.com Published: 2022-06-01 05:09:05 09月13日 Update

# include "server.h"

# include "ui_server.h"

Server::Server (QWidget * parent):

QWidget (parent)

Ui (new Ui::Server)

{

Port = 666,

Socket = new QUdpSocket (this); contains the QUdpSocket class in the .h file, and adds a pointer to the project where network,socket is defined in the .h file

/ / if the binding mode is different according to the system, select the mode through conditional compilation

# ifdef Q_OS_LINUX

Socket- > bind (port, QUdpSocket::ShareAddress)

# else / / Q_OS_WIN32

Socket- > bind (port, QUdpSocket::ReuseAddressHint)

# endif

Connect (socket, SIGNAL (readyRead ()

This, SLOT (readPendingDatagrams ())

Ui- > setupUi (this)

}

Server::~Server ()

{

Delete ui

}

Void Server::readPendingDatagrams () / / start reading data

{

While (socket- > hasPendingDatagrams ())

{

QByteArray datagram

Datagram.resize (socket- > pendingDatagramSize ()); / / obtain the length of the packet through socket

Socket- > readDatagram (datagram.data (), datagram.size ())

DecodeMessage (datagram); / / parse the message

}

}

Void Server::decodeMessage (const QByteArray & ba)

{

QDataStream stream (ba)

QString nick, message

Stream > > nick > > message; / / first read out the first string, assigned to nick (that is, the name), and the second to the message content

ShowMessage (nick, message)

}

/ / used to package messages

QByteArray Server::encodeMessage (const QString & nick, const QString & message) const

{

QByteArray ba

QDataStream stream (& ba, QIODevice::WriteOnly)

Stream text (), / / get the user name

Ui- > textEdit- > toPlainText (); / / get the message

Socket- > writeDatagram (ba, QHostAddress::Broadcast, port); / / initialize Datagram

}

Void Server::showMessage (const QString & nick, const QString & message)

{

QString line = tr ("% 1 says:% 2") .arg (nick) .arg (message)

Ui- > textBrowser- > append (line)

Ui- > textEdit- > clear ()

}

Void Server::on_pushButton_clicked ()

{

SendMessage ()

}

Here is only the .cpp file, which is the logical part of the core. As for the rest, I hope the reader will finish it on his own.

The name of the class used above is Server. In fact, the communication between the two machines does not need a server, as long as it is within a network segment.

Tags: Message data file different name pattern part communication above no between user content character string that is project pointer is on the server Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Docker Linux NVidia macOS