Java 中使用多播的网络发现 [英] Network discovery in Java using multicasting

查看:33
本文介绍了Java 中使用多播的网络发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作客户端/服务器 Java 应用程序.客户端和服务器都将运行在同一个 wi-fi 网络上.服务器将在客户端知道的特定端口上运行.

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.

我计划从客户端通过网络发送一个多播消息,用于该特定端口以发现服务器.但是,我不太确定如何找出网络中的哪个 IP 收到了我的消息.

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?

提前致谢.

推荐答案

(1)server 监听预先安排的端口

(1)server listens on a pre-arranged port

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

(3)client向端口发送消息,在广播IP上,255.255.255.255

(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) 将消息广播到所有本地机器,服务器在 (1) 接收消息,客户端 IP:port.

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

(2) 服务器向客户端 IP:port 发送响应消息

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

(4) 客户端从服务器获取响应消息.

(4) client gets the reponse message from server.

这篇关于Java 中使用多播的网络发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆