Android 中对套接字的非阻塞写入
我有一个打开了套接字的 Android 应用程序。我想写入此套接字,而不会在写入时阻塞线程很长一段时间。如果发生任何 IO 错误,我希望写入会默默地失败。有没有简单的方法可以做到这一点?
I have an Android app that has a Socket open. 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. Is there an easy way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,NIO 提供了
SocketChannel
类(在Socket
上调用getChannel
方法),它允许您调用configureBlocking
以使用非阻塞模式。然后,您应该通过通道而不是通过 Socket 对象执行所有 I/O。Yes, NIO provides a
SocketChannel
class (call thegetChannel
method on yourSocket
), which allows you to callconfigureBlocking
to use non-blocking mode. You should then do all your I/O through the channel, and not through theSocket
object.您可能需要考虑查看 NIO:
http://developer。 android.com/reference/java/nio/channels/package-summary.html
You might want to consider looking at NIO:
http://developer.android.com/reference/java/nio/channels/package-summary.html