我目前正在写一个客户端 - 服务器应用程序,我问自己,如果有更好的方法来找到本地网络中的服务器,然后去低谷所有可用的IP地址,并查看是否正确答案提供?
I am currently writing a client-server application and I ask myself if there is a better way to find a server in the local network then going trough all the available IP addresses and see if the correct answer is supplied?
您可能想看看UDP广播,在您的服务器宣布本身和手机监听广播节目。
You might want to look into UDP broadcasts, where your server announces itself and the phone listens for the broadcasts.
有一个例子,从Boxee的远程项目,下面引用的。
您需要访问无线管理器来获取DHCP信息,并从构建一个广播地址:
You need to access the wifi manager to get the DHCP info and construct a broadcast address from that:
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
已经构造广播地址,一切恢复正常。下面code需要发送字符串数据通过广播,然后等待响应:
Having constructed the broadcast address, things work as normal. The following code would send the string data over broadcast and then wait for a response:
DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
您也可以考虑卓悦/零配置,并有一个 Java实现应该工作在Android上。
You could also look into Bonjour/zeroconf, and there is a Java implementation that should work on Android.