qt编程:windows下的udp通信
本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.
环境:
主机:win7
开发环境:qt
功能:
用udp进行收发通信
界面:
源代码:
LssHost.pro:
- #-------------------------------------------------
- #
- # 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
- #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:
- #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:
- #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