標籤:最簡 size roo bar pac tag exe 通訊 copyto
qt編程:windows下的udp通訊
本文部落格連結:http://blog.csdn.net/jdh99,作者:jdh,轉載請註明.
環境:
主機:win7
開發環境:qt
功能:
用udp進行收發通訊
介面:
原始碼:
LssHost.pro:
[cpp] view plain copy
- #-------------------------------------------------
- #
- # Project created by QtCreator 2013-09-22T09:36:44
- #
- #-------------------------------------------------
-
- QT += core gui
- QT += network
-
- TARGET = LssHost
- TEMPLATE = app
-
-
- SOURCES += main.cpp\
- mainwindow.cpp
-
- HEADERS += mainwindow.h
-
- FORMS += mainwindow.ui
mainwindows.h
[cpp] view plain copy
- #ifndef MAINWINDOW_H
- #define MAINWINDOW_H
-
- #include <QMainWindow>
- #include <QtNetwork/QUdpSocket>
-
- namespace Ui {
- class MainWindow;
- }
-
- class MainWindow : public QMainWindow
- {
- Q_OBJECT
-
- public:
- explicit MainWindow(QWidget *parent = 0);
- ~MainWindow();
-
- private:
- Ui::MainWindow *ui;
-
- QUdpSocket *udp_socket_tx;
- QUdpSocket *udp_socket_rx;
- QHostAddress Ip_Tx;
- int Port_Tx;
-
- private slots:
- void on_btn_cfg_clicked();
- void on_btn_tx_clicked();
- void rx_udp();
- };
-
- #endif // MAINWINDOW_H
mainwindows.cpp:
[cpp] view plain copy
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
-
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
-
- udp_socket_tx = new QUdpSocket(this);
- udp_socket_rx = new QUdpSocket(this);
-
- ui->btn_tx->setEnabled(false);
- }
-
- MainWindow::~MainWindow()
- {
- delete ui;
- }
-
- //接收udp資料
- void MainWindow::rx_udp()
- {
- qDebug() << "rx";
-
- while (udp_socket_rx->hasPendingDatagrams())
- {
- QByteArray datagram;
- datagram.resize(udp_socket_rx->pendingDatagramSize());
-
- QHostAddress sender;
- quint16 senderPort;
-
- udp_socket_rx->readDatagram(datagram.data(), datagram.size(),
- &sender, &senderPort);
-
- ui->txt_rx->append(datagram);
- }
- }
-
- //發送按鍵
- void MainWindow::on_btn_tx_clicked()
- {
- QByteArray datagram = ui->txt_tx->toPlainText().toAscii();
- udp_socket_tx->writeDatagram(datagram, datagram.size(), Ip_Tx, Port_Tx);
- }
-
- //配置按鍵
- void MainWindow::on_btn_cfg_clicked()
- {
- bool ok;
- int port_rx = 0;
-
- //獲得發送IP和連接埠
- Ip_Tx = QHostAddress(ui->txt_ip->text());
- Port_Tx = ui->txt_port_tx->text().toInt(&ok);
- //獲得接收埠
- port_rx = ui->txt_port_rx->text().toInt(&ok);
- udp_socket_rx->bind(QHostAddress::Any, port_rx);
-
- //綁定接收訊號槽
- connect(udp_socket_rx, SIGNAL(readyRead()),this, SLOT(rx_udp()));
-
- ui->btn_tx->setEnabled(true);
- }
main.cpp:
[cpp] view plain copy
- #include <QtGui/QApplication>
- #include "mainwindow.h"
-
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- MainWindow w;
- w.show();
-
- return a.exec();
- }
http://blog.csdn.net/jdh99/article/details/11892725
qt在windows下的udp通訊(最簡單)