qt 简单UDP编程

qt 简单UDP编程dialog.h#ifndefDIALOG_H#defineDIALOG_H#include<QDialog>#include<QUdpSocket>namespaceUi{classDialog;}classDialog:publicQDialog{Q_OBJECTpublic:explicitDia…

大家好,欢迎来到IT知识分享网。qt

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QUdpSocket>

namespace Ui { 
   
class Dialog;
}

class Dialog : public QDialog
{ 
   
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

    QUdpSocket *m_udp;

private slots:
    void on_pushButton_send_clicked();

    void reciveData();

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{ 
   
    ui->setupUi(this);
    m_udp = new QUdpSocket(this);//创建socket套接字
    m_udp->bind(8000);//绑定端口8000
    connect(m_udp,SIGNAL(readyRead()),this,SLOT(reciveData()));//建立接收数据的信号槽
}

Dialog::~Dialog()
{ 
   
    delete ui;
}

void Dialog::on_pushButton_send_clicked()
{ 
   
    QString msg = ui->lineEdit->text();
    if(!msg.isEmpty())
    { 
   
        m_udp->writeDatagram(msg.toUtf8(),QHostAddress("127.0.0.1"),7000);//发送数据
    }
}

void Dialog::reciveData()
{ 
   
    while (m_udp->hasPendingDatagrams())
    { 
   
        quint32 size = m_udp->pendingDatagramSize();
        QByteArray buf(size,0);//size是buf大小,0是初始化数据
        QHostAddress ip;
        quint16 port;
        m_udp->readDatagram(buf.data(),buf.size(),&ip,&port);//接收数据
        ui->textEdit->append("[" + ip.toString() + ":" + QString::number(port) + "] " + buf);
    }
}

main.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{ 
   
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}

https://www.cnblogs.com/wurenzhong/p/8030220.html

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/21537.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信