gpt4 book ai didi

java - ServerSocket.accept() 抛出 SocketTimeoutException 并显示 null 消息

转载 作者:行者123 更新时间:2023-12-01 23:12:58 24 4
gpt4 key购买 nike

我正在尝试从 ServerSocket 对象获取 Socket 的实例。但是,它总是打印

SocketTimeoutException = null

这是我的代码:

try {
// We listen for new connections
Log.d("ShairPort", "Service >> In TRY ");
try {
servSock = new ServerSocket(port);
} catch (IOException e) {
Log.d("ShairPort", "Service >> In TRY # IO Exception = " +e.getMessage());
servSock = new ServerSocket();
}catch(Exception e) {
Log.d("ShairPort", "Service >> In TRY # E xception = " +e.getMessage());
}

// DNS Emitter (Bonjour)
byte[] hwAddr = getHardwareAdress();
emitter = new BonjourEmitter(name, getStringHardwareAdress(hwAddr), port);

//Setting Timeout
servSock.setSoTimeout(10000);


Log.d("ShairPort", "Service >> stopThread = " +stopThread);

while (!stopThread) {
try {
//********** This is throwing Exception ***************//
Socket socket = servSock.accept();
servSock.setReuseAddress(true);
Log.d("ShairPort", "Service >> got connection from " + socket.toString());

new RTSPResponder(hwAddr, socket).start();

} catch(SocketTimeoutException e) {
e.printStackTrace();
Log.d("ShairPort", "Service >> SocketTimeoutException = " + e.getMessage());
//********* here I am getting exception **************//

}catch(Exception e) {
Log.d("ShairPort", "Service >> Exception = " + e.getMessage());
servSock.close();
}
}
} catch (IOException e) {

Log.d("ShairPort", "Service >> TRY # CATCH IOException = " + e.getMessage());
throw new RuntimeException(e);

}

如果我做错了什么,请告诉我,以便我解决此问题。

02-06 18:14:08.300: W/System.err(2245): java.net.SocketTimeoutException
02-06 18:14:08.300: W/System.err(2245): at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:108)
02-06 18:14:08.300: W/System.err(2245): at java.net.ServerSocket.implAccept(ServerSocket.java:203)
02-06 18:14:08.310: W/System.err(2245): at java.net.ServerSocket.accept(ServerSocket.java:128)
02-06 18:14:08.310: W/System.err(2245): at vavi.apps.shairport.LaunchThread.run(LaunchThread.java:99)
02-06 18:14:08.310: W/System.err(2245): Caused by: libcore.io.ErrnoException: accept failed: EAGAIN (Try again)
02-06 18:14:08.320: W/System.err(2245): at libcore.io.Posix.accept(Native Method)
02-06 18:14:08.320: W/System.err(2245): at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:55)
02-06 18:14:08.320: W/System.err(2245): at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
02-06 18:14:08.320: W/System.err(2245): ... 3 more

最佳答案

您正在服务器套接字上设置十秒的超时。

如果十秒内没有连接到达,accept() 方法将抛出 SocketTimeoutException

如果您不希望出现这种行为,请不要设置超时或提高超时。

我不知道为什么当你自己设置超时时你会感到惊讶。

注意,绑定(bind)服务器套接字后,在服务器套接字上调用 setReuseAddress() 是完全没有意义的,更不用说每次接受新连接时了。

关于java - ServerSocket.accept() 抛出 SocketTimeoutException 并显示 null 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com