UDP Broadcast in Java

喜夏-厌秋 提交于 2019-11-27 23:14:51

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?

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.

You can also take a look at MulticastSocket described at Broadcasting to Multiple Recipients. Hope this helps.

If you want to receive a datagram you need to bind() to the local endpoint (address + port).

You are sending and receiving the packet on same device. You could separate send and receive ports (e.g send on 8001, receive on 8002). And run send and receive codes as separate threads. If both device must find each other (or one device find itself).

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

Receiving:

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());
    }
}

Sending:

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());
    }
}

Of course should put this code in a loop in a thread. Based on this example: https://demey.io/network-discovery-using-udp-broadcast/

UPDATE

The link above is dead. But same method described here also: https://www.baeldung.com/java-broadcast-multicast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!