我需要在我的應用程序中同時打開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地址。
你使用什麼地址進行組播? – 2011-05-23 09:13:26
根據我的編輯,這是可配置的。但是,當我嘗試創建MulticastSocket時發生錯誤。它甚至從未到達'joinGroup(address)'行。 – ThaMe90 2011-05-23 09:17:09
你確定,你傳遞給'initBroadCastSocket'的端口是免費的嗎? – 2011-05-23 09:22:50