简体   繁体   English

如何在一个线程上使用不同线程的选择器注册多个SocketChannel

[英]how to register multiple SocketChannel on one thread with a Selector on different thread

I am developing an Android app in which I am using SocketChannel with Selector for sending network requests to my server. 我正在开发一个Android应用程序,其中使用带有Selector的SocketChannel将网络请求发送到我的服务器。

I have a selector on one threads which has registered for OP_CONNECT , OP_WRITE and OP_READ and which calls the select() method to receive these events. 我在一个线程上有一个选择器,该选择器已注册OP_CONNECTOP_WRITEOP_READ ,并调用select()方法接收这些事件。

can anybody suggest me correct way of doing the multi-threaded registration of SocketChannel with a single Selector ? 有人可以建议我使用单个Selector进行SocketChannel的多线程注册的正确方法吗?

The time-consuming part is the actual read from/write to the channels. 耗时的部分是实际对通道的读取/写入。 So basically you would 所以基本上你会

  1. Set up a set of socket channels 设置一组套接字通道
  2. Register all them to a selector. 将它们全部注册到选择器。
  3. In your main selection thread call select() . 在主选择线程中,调用select() Once return value > 0, get the set of selection keys and determine if you want to read/write on the associated channels. 返回值> 0后,获取选择键集并确定是否要在关联的通道上进行读取/写入。
  4. Create a thread pool. 创建一个线程池。 Do all your actual read/write to the channels by that pool. 执行该池对通道的所有实际读取/写入。 Or even, cache your Runnable instances if you want zero object loop. 甚至,如果您希望零对象循环,请缓存您的Runnable实例。

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

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