[英]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.