我的应用程序中有一个TCP套接字。此时它唯一的功能是周期性地发送数据包以保持与服务器的连接。连接成功后,我的循环是:
while (running) {
outputStream.write(0x00);
outputStream.flush();
Thread.sleep(5000 + random.nextInt(5000));
}
但是,有时并且显然是随机的,write
方法会引发以下异常:
java.net.SocketException: sendto failed: EBADF (Bad file descriptor)
at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:542)
at libcore.io.IoBridge.sendto(IoBridge.java:511)
at java.net.PlainSocketImpl.write(PlainSocketImpl.java:500)
at java.net.PlainSocketImpl.-wrap1(PlainSocketImpl.java)
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:266)
at java.io.OutputStream.write(OutputStream.java:82)
at libcore.io.Streams.writeSingleByte(Streams.java:53)
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:262)
at myapp.Service$TCPClient.run(Service.java:174)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.system.ErrnoException: sendto failed: EBADF (Bad file descriptor)
at libcore.io.Posix.sendtoBytes(Native Method)
at libcore.io.Posix.sendto(Posix.java:211)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:278)
at libcore.io.IoBridge.sendto(IoBridge.java:509)
... 8 more
我无法复制错误,有时会发生错误。在下一次迭代中,数据包成功发送,并由服务器接收。始终建立连接。
可能导致此问题以及如何解决问题?