QUdpSocket 简单用法

     UDP是无连接的不可靠的传输协议,可以用在可靠传输不是很重要的情况下使用。 QUdpSocket是QAbstractSocket 的子类,它们都继承了QIODevice。所以可以用QUdpSocket进行发送接收数据。它和QTcpSocket最大的区别也就是,发送数据之前不需要建立连接。以下简单例子,演示了用QUdpSocket如何实现客户端和服务端的通信。

服务端代码:

class UDPServer:public QObject
{
	Q_OBJECT
public:
	UDPServer(QObject *parent = NULL);
	~UDPServer();
private slots:
	void readPendingDatagrams();
private:
	QUdpSocket           *udpSocket;
	
};

UDPServer::UDPServer(QObject *parent /* = NULL */):QObject(parent)
{
	udpSocket = new QUdpSocket(this);
	udpSocket->bind(QHostAddress::LocalHost, 7755);
	cout<<"Server is Running......"<<endl;
	connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
}

UDPServer::~UDPServer()
{

}

void UDPServer::readPendingDatagrams()
{
	QHostAddress sender;
	quint16 senderPort;
	while (udpSocket->hasPendingDatagrams()) 
	{
		QByteArray datagram;
		datagram.resize(udpSocket->pendingDatagramSize());
		udpSocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
		string strMes(datagram);
		std::cout<<strMes<<endl;
	}
	QString text = "hello ...";
	QByteArray datagram = text.toLocal8Bit();
	udpSocket->writeDatagram(datagram.data(),datagram.size(),sender, senderPort);
}


说明:

  1.     我都是在自己的机器上测试,所以服务器地址都是localHost。即
    udpSocket->bind(QHostAddress::LocalHost, 7755);
  2. 给客户端回发信息
    udpSocket->writeDatagram(datagram.data(),datagram.size(),sender, senderPort);

客户端代码:

class UdpClient : public QWidget
{
	Q_OBJECT

public:
	UdpClient(QWidget *parent = 0, Qt::WFlags flags = 0);
	~UdpClient();

private slots:
	void sendMessageSlot();
	void readPendingDatagrams();
private:
	QUdpSocket     *udpSocket;
	QLineEdit      *m_pLEdit;
	QPushButton    *m_pSendMesBtn;
	QLabel         *m_pMessage;
	//Ui::UdpClientClass ui;
};

UdpClient::UdpClient(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags)
{
	m_pLEdit = new QLineEdit(this);
	m_pSendMesBtn = new QPushButton(tr("Sending"),this);
	udpSocket = new QUdpSocket(this);
	m_pMessage = new QLabel(this);
	QHostAddress sender = udpSocket->localAddress();
	quint16 senderPort = udpSocket->localPort();
	udpSocket->bind(sender,senderPort);
	m_pLEdit->setGeometry(5,5,100,20);
	m_pSendMesBtn->setGeometry(110,5,50,20);
	m_pMessage->setGeometry(5,30,150,20);
	m_pLEdit->setStyleSheet("QLineEdit{color:red}");
	connect(m_pSendMesBtn, SIGNAL(clicked()),this, SLOT(sendMessageSlot()));
	connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
	
	//ui.setupUi(this);
	
}

UdpClient::~UdpClient()
{

}

void UdpClient::sendMessageSlot()
{
	QString text = m_pLEdit->text();
	QByteArray datagram = text.toLocal8Bit();
	udpSocket->writeDatagram(datagram.data(),datagram.size(),QHostAddress::LocalHost, 7755);
}

void UdpClient::readPendingDatagrams()
{
	while (udpSocket->hasPendingDatagrams()) 
	{
		QByteArray datagram;
		datagram.resize(udpSocket->pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;
		udpSocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
		QString text = QString(datagram);
		m_pMessage->setText(text);
	}
}
说明:

  1.  绑定本地地址和端口,以接收客户端发过来的信息
    QHostAddress sender = udpSocket->localAddress();
    quint16 senderPort = udpSocket->localPort();
    udpSocket->bind(sender,senderPort);
演示结果图:


发布了102 篇原创文章 · 获赞 26 · 访问量 17万+
展开阅读全文

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官方博客

分享到微信朋友圈

×

扫一扫,手机浏览