Java中的UDP广播 [英] UDP Broadcast in Java

查看:439
本文介绍了Java中的UDP广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上。

我是Java和套接字连接的新手,但我正试图在端口8001上的255.255.255.255上发送UDP数据包/广播到一个设备。我可以将数据发送得很好,但是当接收数据时,连接超时。我有一个数据包嗅探器,我可以看到数据包发送,然后设备响应。

I'm pretty new in Java and socket connections but I'm trying to send out a UDP packet/broadcast on 255.255.255.255 on port 8001 to a device. I can get the data to send just fine, however when it comes time to receive the data the connection times out. I have a packet sniffer and I can see the packet send and then the device respond.

我很确定这是一个新手错误,我在我的错过代码,但我已经坚持了一段时间,任何帮助将不胜感激。

I'm pretty sure it is a rookie mistake that I'm missing in my code but I've been stuck on it for awhile and any help would be appreciated.

 m_Socket = new DatagramSocket(m_SERVERPORT);
 InetAddress address = InetAddress.getByName(m_SERVERIP);


 m_DataPack = new DatagramPacket(m_SERVERCMD.getBytes(), m_SERVERCMD.getBytes().length,
 address, m_SERVERPORT);
 m_Socket.setBroadcast(true);
 m_Socket.connect(address, m_SERVERPORT);

 m_Socket.send(m_DataPack);
 m_DataPack = new DatagramPacket(data, data.length,
 address, m_SERVERPORT);


 m_Socket.receive(m_DataPack); // This is where it times out


 data = m_DataPack.getData();
 String received = data.toString();
 System.out.println("Received: " + received);
 m_Socket.close();

谢谢和Gig'Em。

编辑:

我不确定这是否有帮助但是当我看到m_Socket对象时,我可以在它发送之前看到以下内容:

I'm not sure if this helps but when I watch the m_Socket object I can see the following right before it sends:

bound = true;
close = false;
connectedAddress = Inet4Address (id = 32) (-1,-1,-1,-1);
connectedPort = 8001;
connectState = 1;
created = true;
impl = PlainDatagramSocketImpl;
oldImpl = false;

并且m_DataPack对象如下:

and the m_DataPack object is the following:

address = Inet4Address (id = 32) (-1,-1,-1,-1);
bufLength = 6 (size of packet I'm sending is 6 char long);
offset = 0;
port = 8001;


推荐答案

这没有意义。您正在广播,这是1对多,您也在连接,即1对1。这是什么?

This doesn't make sense. You are broadcasting, which is 1-to-many, and you are also connecting, which is 1-to-1. Which is it?

丢失连接。并输掉255.255.255.255。这已被大约弃用了大约20年。使用子网本地广播地址,例如192.168.1.255。

Lose the connect. And lose the 255.255.255.255. This has been heavily deprecated for about 20 years. Use a subnet-local broadcast address, e.g. 192.168.1.255.

这篇关于Java中的UDP广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆