简体   繁体   English

非阻塞写入 Android 中的套接字

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM