Java 中使用多播的网络发现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3258959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Network discovery in Java using multicasting
提问by mohi666
I'm trying to make a client/server Java App. Both client and server will be running on the same wi-fi network. Server will be running on a specific port that client is aware of.
我正在尝试制作客户端/服务器 Java 应用程序。客户端和服务器都将运行在同一个 wi-fi 网络上。服务器将在客户端知道的特定端口上运行。
I am planning to send a multicast message from client through the network for that specific port to discover the server. However, I'm not too sure how I can find out which IP in my network received my message.
我计划从客户端通过网络发送一个多播消息,用于该特定端口以发现服务器。但是,我不太确定如何找出网络中的哪个 IP 收到了我的消息。
Do I need to create a socket on the client and listen to incoming packets once I send my multicast message in case server replies back?
我是否需要在客户端上创建一个套接字并在我发送多播消息后侦听传入的数据包,以防服务器回复?
Thanks in advance.
提前致谢。
回答by irreputable
(1)server listens on a pre-arranged port
(1)服务器侦听预先安排的端口
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
(3)client向端口发送消息,在广播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.
(3) 将消息广播到所有本地机器,服务器在 (1) 接收消息,客户端 IP:port。
(2) server sends response message to client IP:port
(2)服务器发送响应消息给客户端IP:port
(4) client gets the reponse message from server.
(4) 客户端从服务器获取响应消息。
回答by Romain Hippeau
回答by J?rg
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, hazelcastetc. that plain Java API might serve you well enough.
您可以尝试使用java.net.MulticastSocket(自 Java 1.1 起可用)。如果您不需要像jgroups、hazelcast等库的丰富功能集,那么纯 Java API 可能足以为您服务。
回答by Anon
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.
您可以尝试使用SSDP。这是 UPnP 设备用来发现彼此的东西。它在端口 1900 上进行多播,并且只使用非常简单的数据包来发送 IP 和服务信息。
Clingis a UPnP lib you can pull from. Note I'm not recommending you move to UPnP - just the discovery protocol used.
Cling是一个可以从中提取的 UPnP 库。注意我不建议您转向 UPnP - 只是使用的发现协议。

