简体   繁体   中英

UDP broadcast client in Java

I am using UDP broadcast for interservice communication The server is in Python and I can see the UDP messages using this code:

import sys
import socket

HOST = ''
PORT = 9002

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.bind((HOST,PORT))

while True:
    try:
        message = s.recv(8192)
        print("Got data: " + message)
    except KeyboardInterrupt:
        sys.exit()

I can run as many of these clients simultaneously as I want on the same machine.

I'm trying to implement a similar client in Java using the DatagramSocket class, but I keep getting an "address already in use" error. Evidently I need to construct it differently than I am currently:

DatagramSocket socket = new DatagramSocket(broadcastPort);

Is it possible to get the same behavior as the Python code?

Try this:

// create an unbound socket
DatagramSocket socket = new DatagramSocket(null);

// make it possible to bind several sockets to the same port
socket.setReuseAddress(true);

// might not be necessary, but for clarity
socket.setBroadcast(true);

socket.bind(new InetSocketAddress(9002));

The null argument to the constructor is the key here. That wisdom is hidden in the second paragraph of the javadoc for the DatagramSocket(SocketAddress bindAddress) constructor:

if the address is null, creates an unbound socket.

Address already in use probably means you haven't properly terminated your programs. If you're using Eclipse, make sure you check all your open consoles and terminate all of them. (Top right corner, blue box - click it and it'll show all running programs)

In Eclipse, just because you "run" your program again, it doesn't terminate the previous one(s).

Another possible issue is that you may be using the same port as your python server. 2 Applications can't claim the same port, so just change the port number if that is the case.

Edit: Use a MulticastSocket .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM