[英]Non-blocking write to a socket in Android
I have an Android app that has a Socket open.我有一个打开 Socket 的 Android 应用程序。 I would like to write to this socket without any possibility of blocking the thread on the write for a noticeable amount of time.
我想写入这个套接字,而没有任何可能在相当长的时间内阻塞写入线程。 If any IO error occurs, I would like the write to just silently fail.
如果发生任何 IO 错误,我希望写入只是静默失败。 Is there an easy way to do this?
是否有捷径可寻?
Yes, NIO provides a SocketChannel
class (call the getChannel
method on your Socket
), which allows you to call configureBlocking
to use non-blocking mode.是的,NIO 提供了一个
SocketChannel
class(在你的Socket
上调用getChannel
方法),它允许你调用configureBlocking
来使用非阻塞模式。 You should then do all your I/O through the channel, and not through the Socket
object.然后,您应该通过通道而不是通过
Socket
object 执行所有 I/O。
You might want to consider looking at NIO:您可能需要考虑查看 NIO:
http://developer.android.com/reference/java/nio/channels/package-summary.html http://developer.android.com/reference/java/nio/channels/package-summary.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.