我需要在我的应用程序中同时打开2个不同的套接字。一个是标准DatagramSocket,另一个是MulticastSocket。两者都有自己的端口。但是,当我尝试初始化它们时,我在创建第二个套接字时出错。错误如下:
05-23 10:37:57.011: ERROR/UDPInterface(15478): Exception occurred while initializing MulticastSocket: java.net.BindException: Address already in use
但是,因为我为两个套接字使用单独的端口,所以这不可能发生,对吧?或者是因为为MulticastSocket指定的端口已经在使用?然后错误消息没有任何意义,因为它正在谈论已经在使用的地址....:/
我创建了这样的套接字:
/**
* Initially set the UnicastSocket to use.
* <p>Called from the constructor to create a new DatagramSocket to use
* for receiving and sending unicast data over UDP.
* @param address The address to initially use.
* @param port The port to initially use.
*/
private void initUnicastSocket(Inet4Address address, int port){
try{
mUnicastSocket = new DatagramSocket(port, address);
mUnicastSocket.setSoTimeout(SOCKET_TIME_OUT);
} catch(SocketException se){
Log.e(TAG, "Exception occurred while initializing UnicastSocket: " + se.toString());
}
if(mUnicastSocket != null){
Log.d(TAG, "Socket initially set to " +
mUnicastSocket.getLocalAddress() + ":" + UnicastSocket.getLocalPort());
}
}
/**
* Initially set the BroadcastSocket to use.
* <p>Called from the constructor to create a new MulticastSocket to use
* for receiving and sending broadcast data over UDP.
* @param address
* @param port
*/
private void initBroadcastSocket(Inet4Address address, int port){
try {
mBroadcastSocket = new MulticastSocket(port);
mBroadcastSocket.joinGroup(address);
mBroadcastSocket.setSoTimeout(SOCKET_TIME_OUT);
} catch (IOException ioe) {
Log.e(TAG, "Exception occurred while initializing MulticastSocket: " + ioe.toString());
}
if(mBroadcastSocket != null){
Log.d(TAG, "MulticastSocket initially set to " + mBroadcastSocket.getLocalAddress() +
":" + mBroadcastSocket.getLocalPort());
}
}
修改 的
值得注意的是,普通的DatagramSocket将使用设备的IP地址,而MulticastSocket将使用可由用户配置的IP地址。
答案 0 :(得分:1)
多播使用UDP数据包加上错误消息“初始化 MulticastSocket ”,因此问题是多播套接字。
我建议将套接字参数添加到日志消息中。这将使调试变得更加简单。
您的体验有以下几个原因:
答案 1 :(得分:0)
我通过使用辅助DatagramSocket而不是MulticastSocket解决了这个问题。通过设置DatagramSocket.setBroadcast(true);
,我可以发送/接收广播消息。
修改初始化逻辑:
/**
* Initially set the BroadcastSocket to use.
* <p>Called from the constructor to create a new DatagramSocket to use
* for receiving and sending broadcast data over UDP.
* @param address
* @param port
*/
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());
}
}
谢谢大家虽然为我花了很多时间。