首页 > 代码库 > qt在windows下的udp通信(最简单)
qt在windows下的udp通信(最简单)
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通信(最简单)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。