QUdpSocket使用整理

效果图
这里写图片描述

服务端源码
注意:在.pro中添加QT += network

udpserver.h

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QUdpSocket>
#include <QTimer>

class UdpServer : public QDialog
{
    Q_OBJECT

public:
    UdpServer(QWidget *parent = 0,Qt::WindowFlags f=0);
    ~UdpServer();
public slots:
    void StartBtnClicked();//点击开始按钮
    void timeout();//一段时间后执行函数
private:
    QLabel *TimerLabel;
    QLineEdit *TextLineEdit;//发送内容的lineedit
    QPushButton *StartBtn;//开始按钮
    QVBoxLayout *mainLayout;//布局
    int port;//端口号
    bool isStarted;//是否开始
    QUdpSocket *udpSocket;//udp
    QTimer *timer;//计时器
};

#endif // UDPSERVER_H

udpserver.cpp

#include "udpserver.h"
#include <QHostAddress>

UdpServer::UdpServer(QWidget *parent, Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle(tr("UDP Server"));

    TimerLabel = new QLabel(tr("计时器:"),this);
    TextLineEdit = new QLineEdit(this);
    StartBtn = new QPushButton(tr("开始"),this);

    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(TimerLabel);
    mainLayout->addWidget(TextLineEdit);
    mainLayout->addWidget(StartBtn);

    connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));

    port =5555;
    isStarted=false;
    udpSocket = new QUdpSocket(this);
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));
}

UdpServer::~UdpServer()
{

}

void UdpServer::StartBtnClicked()
{
    if(!isStarted)
    {
        StartBtn->setText(tr("停止"));
        timer->start(1000);//每1秒执行一次timeout()
        isStarted =true;
    }
    else
    {
        StartBtn->setText(tr("开始"));
        isStarted = false;
        timer->stop();//停止
    }
}

void UdpServer::timeout()
{
    QString msg = TextLineEdit->text();
    int length=0;
    if(msg=="")
    {
       return;
    }
    //通过udp写入传输数据
    if((length=udpSocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
    {
        return;
    }
}

客户端源码
注意:在.pro中添加QT += network
udpclient.h

#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include <QDialog>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QUdpSocket>

class UdpClient : public QDialog
{
    Q_OBJECT

public:
    UdpClient(QWidget *parent = 0,Qt::WindowFlags f=0);
    ~UdpClient();    
public slots:
    void CloseBtnClicked();//点击关闭按钮
    void dataReceived();//点击接受按钮
private:
    QTextEdit *ReceiveTextEdit;//接受的内容
    QPushButton *CloseBtn;//关闭
    QVBoxLayout *mainLayout;//布局
    int port;//端口号
    QUdpSocket *udpSocket;//udp
};

#endif // UDPCLIENT_H

udpclient.cpp

#include "udpclient.h"
#include <QMessageBox>
#include <QHostAddress>

UdpClient::UdpClient(QWidget *parent,Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle(tr("UDP Client"));

    ReceiveTextEdit = new QTextEdit(this);
    CloseBtn = new QPushButton(tr("Close"),this);

    mainLayout=new QVBoxLayout(this);
    mainLayout->addWidget(ReceiveTextEdit);
    mainLayout->addWidget(CloseBtn);

    connect(CloseBtn,SIGNAL(clicked()),this,SLOT(CloseBtnClicked()));

    port =5555;

    udpSocket = new QUdpSocket(this);
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));

    bool result=udpSocket->bind(port);
    //当绑定失败时弹出提示
    if(!result)
    {
        QMessageBox::information(this,tr("error"),tr("udp socket create error!"));
        return;
    }
}

UdpClient::~UdpClient()
{

}

void UdpClient::CloseBtnClicked()
{
    close();
}

void UdpClient::dataReceived()
{
    //通过udp接收数据
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        //读取数据
        udpSocket->readDatagram(datagram.data(),datagram.size());
        QString msg=datagram.data();
        //向textdit中插入数据
        ReceiveTextEdit->insertPlainText(msg);
    }
}
发布了149 篇原创文章 · 获赞 35 · 访问量 16万+
展开阅读全文

UDP给指定IP和端口传输数据包,为什么一直显示Network is unreachable: Datagram send failed

11-25

**_ UDPClient.java** package com.bill.udp.client; import java.io.IOException; import java.io.RandomAccessFile; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import com.bill.udp.util.UDPUtils; public class UDPClient { private static final String SEND_FILE_PATH = "D:/imgmap.jpg"; public static void main(String[] args){ long startTime = System.currentTimeMillis(); byte[] buf = new byte[UDPUtils.BUFFER_SIZE]; byte[] receiveBuf = new byte[1]; RandomAccessFile accessFile = null; DatagramPacket dpk = null; DatagramSocket dsk = null; int readSize = -1; try { accessFile = new RandomAccessFile(SEND_FILE_PATH,"r"); //构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。 dpk = new DatagramPacket(buf, buf.length,new InetSocketAddress(InetAddress.getByName("192.168.1.106"), 5000)); //创建数据报套接字,将其绑定到指定的本地地址。 dsk = new DatagramSocket(5001, InetAddress.getByName("192.168.1.106")); int sendCount = 0; while((readSize = accessFile.read(buf,0,buf.length)) != -1){ dpk.setData(buf, 0, readSize); dsk.send(dpk); // wait server response { while(true){ dpk.setData(receiveBuf, 0, receiveBuf.length); dsk.receive(dpk); // confirm server receive if(!UDPUtils.isEqualsByteArray(UDPUtils.successData,receiveBuf,dpk.getLength())){ System.out.println("resend ..."); dpk.setData(buf, 0, readSize); dsk.send(dpk); }else break; } } System.out.println("send count of "+(++sendCount)+"!"); } // send exit wait server response while(true){ System.out.println("client send exit message ...."); dpk.setData(UDPUtils.exitData,0,UDPUtils.exitData.length); dsk.send(dpk); dpk.setData(receiveBuf,0,receiveBuf.length); dsk.receive(dpk); if(!UDPUtils.isEqualsByteArray(UDPUtils.exitData, receiveBuf, dpk.getLength())){ System.out.println("client Resend exit message ...."); dsk.send(dpk); }else break; } }catch (Exception e) { e.printStackTrace(); } finally{ try { if(accessFile != null) accessFile.close(); if(dsk != null) dsk.close(); } catch (IOException e) { e.printStackTrace(); } } long endTime = System.currentTimeMillis(); System.out.println("time:"+(endTime - startTime)); } } **UDPUtils.java** package com.bill.udp.util; public class UDPUtils { private UDPUtils(){} /** transfer file byte buffer **/ public static final int BUFFER_SIZE = 50 * 1024; /** controller port **/ public static final int PORT = 50000; /** mark transfer success **/ public static final byte[] successData = "success data mark".getBytes(); /** mark transfer exit **/ public static final byte[] exitData = "exit data mark".getBytes(); public static void main(String[] args) { byte[] b = new byte[]{1}; System.out.println(isEqualsByteArray(successData,b)); } public static boolean isEqualsByteArray(byte[] compareBuf,byte[] buf){ if (buf == null || buf.length == 0) return false; boolean flag = true; if(buf.length == compareBuf.length){ for (int i = 0; i < buf.length; i++) { if(buf[i] != compareBuf[i]){ flag = false; break; } } }else return false; return flag; } public static boolean isEqualsByteArray(byte[] compareBuf,byte[] buf,int len){ if (buf == null || buf.length == 0 || buf.length < len || compareBuf.length < len) return false; boolean flag = true; int innerMinLen = Math.min(compareBuf.length, len); for (int i = 0; i < innerMinLen; i++) { if(buf[i] != compareBuf[i]){ flag = false; break; } } return flag; } } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览