[英]Having multiple sockets open at the same time
我需要在我的應用程序中同時打開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地址。
多播使用UDP數據包,加上錯誤消息“初始化MulticastSocket時 ”,因此問題出在多播套接字上。
我建議將套接字參數添加到日志消息中。 這將使調試更加簡單。
您遇到的原因可能有幾個原因:
我已經通過使用輔助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());
}
}
不過,謝謝大家為我花時間在此上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.