Network discovery in Java using multicasting

邮差的信 提交于 2019-11-28 06:30:00

(1)server listens on a pre-arranged port

DatagramSocket s = new DatagramSocket(8888);
s.receive  //(1)
s.send     //(2)

(3)client sends a message to the port, on the broadcast IP, 255.255.255.255

DatagramSocket c = new DatagramSocket();
c.send(255.255.255.255:8888,msg)     //(3)
c.receive  //(4)

the client binds to a port too. we didn't specify it, so it's random chosen for us.

(3) will broadcast the message to all local machines, server at (1) receives message, with the client IP:port.

(2) server sends response message to client IP:port

(4) client gets the reponse message from server.

I would strongly recommend using JGroups. It has a lot of features and it will do all the UDP stuff. JBoss uses it for their clustering.

You can try using java.net.MulticastSocket (available since Java 1.1). If you don't need the rich feature sets of libs like jgroups, hazelcast etc. that plain Java API might serve you well enough.

See also example pages here and here.

You could try using SSDP. It's what UPnP devices use to discover each other. It's multicast on port 1900 and just uses really simple packets to send around IPs and service information.

Cling is a UPnP lib you can pull from. Note I'm not recommending you move to UPnP - just the discovery protocol used.

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