Note that there are some explanatory texts on larger screens.

plurals
  1. POSeparate threads for input and output in Java TCP Server
    primarykey
    data
    text
    <p>I've been tasked with writing a tcp server and client in Java. I'm having some trouble working out the general structure of my server. The server must accept multiple connections but there is no request response protocol. Once a connection is made, the client can send data to the server, and the server can send data to the client. Given this, I decided it would be a good idea for each connection to have seperate input and output threads. I've looked through lots of examples but most are quite simple and don't have separate threads for input and output. I'd greatly appreciate any help or advice.</p> <p>So far, my the tcp server has a listening thread which listens for client connections. Once a connection is made, I create an input thread and an output thread for that connection.</p> <p>In TCPServer</p> <pre><code>while (true) { SocketChannel clientChannel = m_serverChannel.accept(); new Thread(new ReadWorker(clientChannel)).start(); new Thread(new WriteWorker(clientChannel)).start(); } </code></pre> <p>How should I pass the data to be sent to the output threads? My initial thoughts were to have the output threads listen on a queue of pending data, sending the data as it becomes available.</p> <p>In TCPServer</p> <pre><code>ConcurrentHashMap&lt;SocketChannel, LinkedBlockingQueue&lt;ByteBuffer&gt;&gt; pendingWrites = new ConcurrentHashMap&lt;SocketChannel, LinkedBlockingQueue&lt;ByteBuffer&gt;&gt;(); void broadcast(ByteBuffer buffer) { synchronized(pendingWrites) { Iterator it = pendingWrites.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); ((LinkedBlockingQueue&lt;ByteBuffer&gt;) pairs.getValue()).put(buffer); } } </code></pre> <p>In WriteWorker</p> <pre><code>pendingWrites.get(socketChannel).take() // send the data </code></pre> <p>Is this a reasonable solution?</p> <p>The other problem I'm having is if one worker fails due to client disconnection, how can I communicate this to the other thread? If there is a failure in one thread, I'd like to terminate the other.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload