吉吉于

free

Qt学习笔记(2):Udp局域网通信

</embed>

 

和朋友准备做一个手机控制灯光的开关这么一个小东西。

用到Qt写N8的程序,现处于初级阶段,以此文留念。

Sender:

.cpp

01 #include “widget.h”
02 #include “ui_widget.h”
03
04 Widget::Widget(QWidget *parent) :
05     QWidget(parent),
06     ui(new Ui::Widget)
07 {
08     ui->setupUi(this);
09     sender=new QUdpSocket(this);
10 }
11
12 Widget::~Widget()
13 {
14     delete ui;
15 }
16 void Widget::on_pushButton_clicked()
17 {
18     QByteArray datagram =“ON!”;
19     sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress(ui->lineEdit->text()),45454);
20 }
21 void Widget::on_pushButton_2_clicked()
22 {
23     QByteArray datagram =“OFF!”;
24     sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress(ui->lineEdit->text()),45454);
25 }

.h

 

C++语言: Codee#23278
01 #ifndef WIDGET_H
02 #define WIDGET_H
03
04 #include </span>
05 #include </span>
06 namespace Ui {
07     class Widget;
08 }
09
10 class Widget : public QWidget
11 {
12     Q_OBJECT
13
14 public:
15     explicit Widget(QWidget *parent = );
16     ~Widget();
17 private slots:
18     void on_pushButton_clicked();
19     void on_pushButton_2_clicked();
20 private:
21     Ui::Widget *ui;
22     QUdpSocket *sender;
23 };
24
25 #endif // WIDGET_H </div> Receiver .cpp
01 #include “widget.h”
02 #include “ui_widget.h”
03
04 Widget::Widget(QWidget *parent) :
05     QWidget(parent),
06     ui(new Ui::Widget)
07 {
08     ui->setupUi(this);
09     receiver=new QUdpSocket(this);
10     receiver->bind(45454,QUdpSocket::ShareAddress);
11     connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
12 }
13
14 Widget::~Widget()
15 {
16     delete ui;
17 }
18 void Widget::processPendingDatagram()
19 {
20     while(receiver->hasPendingDatagrams())
21     {
22         QByteArray datagram;
23         datagram.resize(receiver->pendingDatagramSize());
24         receiver->readDatagram(datagram.data(),datagram.size());
25         ui->label->setText(datagram);
26
27     }
28 }
.h
01 #ifndef WIDGET_H
02 #define WIDGET_H
03
04 #include </span>
05 #include </span>
06 namespace Ui {
07     class Widget;
08 }
09
10 class Widget : public QWidget
11 {
12     Q_OBJECT
13
14 public:
15     explicit Widget(QWidget *parent = );
16     ~Widget();
17 private slots:
18     void processPendingDatagram();
19 private:
20     Ui::Widget *ui;
21     QUdpSocket *receiver;
22 };
23
24 #endif // WIDGET_H </div> 下载源码 转载请注明:[于哲的博客][1] » [Qt学习笔记(2):Udp局域网通信][2] [1]: http://lazynight.me [2]: http://lazynight.me/542.html