server.ui
client和server.ui完全相同!!!!
server.h/.cpp
class Server : public QMainWindow
{.....
private:Ui::Server *ui;QUdpSocket *server;
};--------------------#include "server.h"
#include "ui_server.h"
#include <QPushButton>
#include <QImage>
Server::Server(QWidget *parent) :QMainWindow(parent),ui(new Ui::Server)
{ui->setupUi(this);//实例化一个socket套节字server = new QUdpSocket(this);ui->ip1->setText("127.0.0.1");ui->port1->setText("8090");ui->port2->setText("6060");//绑定自己的端口server->bind(ui->port2->text().toInt());//发送数据connect(ui->send,&QPushButton::clicked,this,[=](){server->writeDatagram(ui->input->toPlainText().toUtf8(),QHostAddress(ui->ip1->text()),ui->port1->text().toInt());ui->record->append("来自宗介的:"+ui->input->toPlainText());ui->input->clear();});//接收数据connect(server,&QUdpSocket::readyRead,this,[=](){//返回值qint64 ------ 获取即将要接收的数据报文的大小qint64 size = server->pendingDatagramSize();QByteArray array(size,0);server->readDatagram(array.data(),size);ui->record->append("来自波妞的:"+array);});}Server::~Server()
{delete ui;
}
client.h/.cpp
Client::Client(QWidget *parent) :QMainWindow(parent),ui(new Ui::Client)
{ui->setupUi(this);ui->ip1->setText("127.0.0.1");ui->port1->setText("6060");ui->port2->setText("8090");client = new QUdpSocket(this);//绑定自己的端口client->bind(ui->port2->text().toInt());//发送数据connect(ui->send,&QPushButton::clicked,this,[=](){client->writeDatagram(ui->input->toPlainText().toUtf8(),QHostAddress(ui->ip1->text()),ui->port1->text().toInt() );ui->record->append("来自波纽的:"+ui->input->toPlainText());ui->input->clear();});//接收数据connect(client,&QUdpSocket::readyRead,this,[=](){qint64 size = client->pendingDatagramSize();QByteArray array(size,0);client->readDatagram(array.data(),size);ui->record->append("来自宗介的:"+array);});}
端口号一定要尽可能大!!!!!
广播
例如前面在UDP中, 我们发送信息都是指定发送的内容,对方的IP地址和对方的端口号,相当于给一个人发信息。广播的意义在于给好多人发消息。
于是IP换一下就成为广播了。
//广播server->writeDatagram(ui->input->toPlainText().toUtf8(),QHostAddress::Broadcast,ui->port1->text().toInt());//255.255.255.255
组播
例如服务器要进行组播,组播的话要进行设置组播段号,同时还需要要自身绑定更改
server->bind(QHostAddress::AnyIPv4);
//加入组播server->joinMulticastGroup(QHostAddress("244.0.0.10"));server->writeDatagram(ui->input->toPlainText().toUtf8(),QHostAddress("224.0.0.10"),ui->port1->text().toInt());