1  简介

参考视频:https://www.bilibili.com/video/BV1XW411x7NU?p=61

说明:UDP是面向无连接的,客户端并不与服务器不建立连接,直接向服务器发送数据,服务器端也不从客户端接收连接,只负责调用接收函数,等待客户端连接的到达。

udp通信模型如下:

Qt-udp通信

 (1)服务器端

1)创建套接字;

2)绑定套接字;

3)接收或发送数据;

4)关闭连接。

(2)客户端

1)创建套接字;

2)接收或发送数据;

3)关闭连接。

2  测试说明

(1)基本udp测试

功能:创建一个窗口,使用127.0.0.1:8888进行回环测试,自发自收。

实现步骤:

创建套接字并绑定端口,不指定ip:

1     QUdpSocket *udpsocket = NULL;
2     //创建套接字,指定父对象
3     udpsocket = new QUdpSocket(this);
4     //绑定
5     udpsocket->bind(8888);

送数据:

 1     //先获取对方的ip和端口
 2     QString ip = ui->lineEdit_ip->text();
 3     qint16 port = ui->lineEdit_port->text().toInt();
 4     //获取编辑区内容
 5     QString str = ui->textEdit_send->toPlainText();
 6     if (str.isEmpty()) {
 7         return;
 8     }
 9     //给指定的IP发送数据
10     udpsocket->writeDatagram(str.toUtf8(), QHostAddress(ip), port);

接收数据:

 1     //当对方成功发送数据过来,会自动触发readyRead()信号
 2     connect(udpsocket, &QUdpSocket::readyRead,
 3         [=](){
 4             //读取对方发送的数据
 5             char buf[1024] = {0};
 6             QHostAddress cli_addr;  //对方地址
 7             quint16 port;  //对方端口
 8             qint64 len = udpsocket->readDatagram(buf, sizeof(buf), &cli_addr, &port);
 9             if (len > 0) {
10                 //格式化[192.168.2.2:8888]aaaa
11                 QString str = QString("[%1:%2] %3").arg(cli_addr.toString()).arg(port).arg(buf);
12                 //给编辑区设置内容
13                 ui->textEdit_recv->append(str);
14             }
15         }
16     );

完整代码如下:

widget.h

 1 #ifndef WIDGET_H
 2 #define WIDGET_H
 3 
 4 #include <QWidget>
 5 #include <QUdpSocket>
 6 
 7 namespace Ui {
 8 class Widget;
 9 }
10 
11 class Widget : public QWidget
12 {
13     Q_OBJECT
14 
15 public:
16     explicit Widget(QWidget *parent = 0);
17     ~Widget();
18 
19 private slots:
20     void on_pushButton_send_clicked();
21 
22     void on_pushButton_close_clicked();
23 
24 private:
25     Ui::Widget *ui;
26     QUdpSocket *udpsocket = NULL;
27 };
28 
29 #endif // WIDGET_H
View Code

相关文章:

  • 2022-12-23
  • 2021-06-27
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2017-12-12
  • 2021-09-09
  • 2021-10-08
  • 2021-05-28
  • 2021-11-24
相关资源
相似解决方案