我正在尝试制作一个客户端/服务器 Java 应用程序。客户端和服务器都将在同一 Wi-Fi 网络上运行。服务器将在客户端知道的特定端口上运行。
我计划通过网络从客户端向该特定端口发送多播消息以发现服务器。但是,我不太确定如何找出网络中的哪个 IP 收到了我的消息。
我是否需要在客户端上创建一个套接字,并在发送多播消息后侦听传入的数据包,以防服务器回复?
提前致谢。
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.
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.
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.
发布评论
评论(4)
(1)服务器监听预先安排的端口
(3)客户端向该端口发送消息,在广播 IP 255.255.255.255 上
客户端也绑定到端口。我们没有指定它,所以它是我们随机选择的。
(3)将消息广播到所有本地机器,(1)处的服务器接收消息,带有客户端IP:端口。
(2) 服务器向客户端IP:端口发送响应消息
(4) 客户端从服务器获取响应消息。
(1)server listens on a pre-arranged port
(3)client sends a message to the port, on the broadcast IP, 255.255.255.255
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.
我强烈建议使用 JGroups。它有很多功能并且可以完成所有 UDP 的工作。 JBoss 将其用于集群。
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.
您可以尝试使用
java.net.MulticastSocket
(自 Java 1.1 起可用)。如果您不需要库的丰富功能集,例如 jgroups、hazelcast 等简单的 Java API 可能足以为您服务。另请参阅此处和这里。
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.
您可以尝试使用 SSDP。 UPnP 设备使用它来发现彼此。它在端口 1900 上进行多播,仅使用非常简单的数据包来发送 IP 和服务信息。
Cling 是一个 UPnP 库,您可以从中获取。注意我不建议您迁移到 UPnP - 只是使用发现协议。
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.