Java中的UDP广播

问题描述 投票:6回答:4

早上。

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

我很确定这是我在代码中遗漏的新手错误,但我已经坚持了一段时间,任何帮助都会受到赞赏。

 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对象时,我可以在发送之前看到以下内容:

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

并且m_DataPack对象如下:

address = Inet4Address (id = 32) (-1,-1,-1,-1);
bufLength = 6 (size of packet I'm sending is 6 char long);
offset = 0;
port = 8001;
java udp broadcast
4个回答
11
投票

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

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


3
投票

您还可以查看Broadcasting to Multiple Recipients中描述的MulticastSocket。希望这可以帮助。


1
投票

如果要接收数据报,则需要将bind()发送到本地端点(地址+端口)。


0
投票

您正在同一设备上发送和接收数据包。您可以分开发送和接收端口(例如,发送8001,接收8002)。并将发送和接收代码作为单独的线程运行。如果两个设备必须找到彼此(或一个设备找到自己)。

import java.io.IOException;
import java.net.*;

接收:

private DatagramSocket getReceiveSocket() throws UnknownHostException, SocketException {
    if (receiveSocket == null) {
        receiveSocket = new DatagramSocket(8002, InetAddress.getByName("0.0.0.0")); // 0.0.0.0 for listen to all ips
        receiveSocket.setBroadcast(true);
    }
    return receiveSocket;
}

public void receive() throws IOException {
    // Discovery request command
    byte[] buffer = "__DISCOVERY_REQUEST__".getBytes();
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    getReceiveSocket().receive(packet);
    System.out.println("Discovery package received! -> " + packet.getAddress() + ":" + packet.getPort());
    // Get received data
    String data = new String(packet.getData()).trim();
    if (data.equals("__DISCOVERY_REQUEST__")) { // validate command
        // Send response
        byte[] response = new byte["__DISCOVERY_RESPONSE".length()];
        DatagramPacket responsePacket = new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
        getReceiveSocket().send(responsePacket);
        System.out.println("Response sent to: " + packet.getAddress() + ":" + packet.getPort());
    } else {
        System.err.println("Error, not valid package!" + packet.getAddress() + ":" + packet.getPort());
    }
}

发送:

private DatagramSocket getSendSocket() throws UnknownHostException, SocketException {
    if (sendSocket == null) {
        sendSocket = new DatagramSocket(8001, InetAddress.getLocalHost());
        sendSocket.setBroadcast(true);
    }
    return sendSocket;
}

public void send() throws IOException {
    // Discovery request command
    byte[] data = "__DISCOVERY_REQUEST__".getBytes();
    DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), 8002);
    getSendSocket().send(packet);
    System.out.println("Discovery package sent!" + packet.getAddress() + ":" + packet.getPort());

    // Discovery response command
    byte[] response = new byte["__DISCOVERY_RESPONSE__".length()];
    DatagramPacket responsePacket = new DatagramPacket(response, response.length);
    getSendSocket().receive(responsePacket);
    System.out.println("Discovery response received!" + responsePacket.getAddress() + ":" + responsePacket.getPort());
    String responseData = new String(responsePacket.getData()).trim();
    if (responseData.equals("__DISCOVERY_RESPONSE__")) { // Check valid command
        System.out.println("Found buddy!" + responsePacket.getAddress() + ":" + responsePacket.getPort());
    }
}

当然应该把这段代码放在一个线程的循环中。基于这个例子:https://demey.io/network-discovery-using-udp-broadcast/

UPDATE

上面的链接已经死了。但是这里描述的方法也一样:https://www.baeldung.com/java-broadcast-multicast

© www.soinside.com 2019 - 2024. All rights reserved.