我在将数据报数据包从一部 Android 手机广播到另一部手机时遇到问题。
我已将我的应用程序设置为能够使用 2 个不同的数据报套接字。这一切都很好,我能够在套接字之间切换就好了。
我使用 2 部手机来测试应用程序,以及能够与我的应用程序通信的基于 PC 的应用程序。当我尝试从两部手机中的一部广播数据报数据包时,PC 应用程序反应良好,但另一部手机根本没有响应。当我用另一部手机尝试时也会发生同样的情况。
但问题是:每当我尝试从基于 PC 的应用程序进行广播时,两部手机都会响应。(???)
设备和 PC 应用程序都设置为使用相同的广播地址进行发送。然而,电话似乎不接受对方的广播。我已经确认他们在广播时确实收到了自己的广播响应,这显然是正确的。
我用来初始化和更新广播套接字的方法如下所述。
private void initBroadcastSocket(Inet4Address address, int port){
try {
mBroadcastSocket = new DatagramSocket(port, address);
mBroadcastSocket.setBroadcast(true);
mBroadcastSocket.setSoTimeout(SOCKET_TIME_OUT);
} catch (IOException ioe) {
Log.e(TAG, "Exception occurred while initializing BroadcastSocket: " + ioe.toString());
}
if(mBroadcastSocket != null){
Log.d(TAG, "BroadcastSocket initially set to " + mBroadcastSocket.getLocalAddress() +
":" + mBroadcastSocket.getLocalPort());
}
}
public synchronized void updateBroadcastSocket(Inet4Address address, int port){
// Temporarily suspend the listening Thread.
...
// If the socket is open, close it.
if(mBroadcastSocket != null){
mBroadcastSocket.close();
mBroadcastSocket = null;
}
// Create new socket with the passed values.
try {
mBroadcastSocket = new DatagramSocket(port, address);
mBroadcastSocket.setBroadcast(true);
mBroadcastSocket.setSoTimeout(SOCKET_TIME_OUT);
} catch (SocketException se) {
Log.e(TAG, "Exception occured while updating BroadcastSocket: " + se.toString());
}
// Log new address and port.
...
// Continue the listening Thread.
...
}
如果有人发现我的代码有缺陷,请详细说明。