简体   繁体   中英

How to read SocketChannel in one thread, and write from n threads?

I have a socketChannel (java.nio.channels.SocketChannel) listening for reading requests (from multiple clients). It stores each request in a Request Queue .

Also socketChannel.configureBlocking(false)

Then I want the multiple threads to take one request at a time from the R equest Queue and write to the socketChannel

I have read the following from a documentation.

Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time.

Since only 1 thread can be written, what can I do in the case of multiple writes?

You can use your own lock synchronized or ReentrantLock , or queue the messages and have one thread do the actual writes.

The problem with writes is you can only atomically write one byte at a time, if you write more than one byte, you might send some, but not all of the data in which case another thread can attempt to write it's message and you get a corrupted message.

I have a java.nio.channels.SocketChannel listening for reading requests (from multiple clients).

No you don't. You might have a ServerSocketChannel that listens for connections from multiple clients, but once you have an accepted SocketChannel , it is only connected to one client. All you can get from it is sequential requests from that client.

It stores each request in a Request Queue.

I don't see any need for that.

Also socketChannel.configureBlocking(false)

Then I want the multiple threads to take one request at a time from the Request Queue and write to the socketChannel

Why not just compute the reply as soon as you read it and write it directly back?

I have read the following from a documentation.

Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time.

Since only 1 thread can be written, what can I do in the case of multiple writes?

What multiple writes? You only have one client request per channel. You only need to write one reponse per request. You should not read, let alone process, a new request until you've written the prior response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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