Java stateful multi-threaded server - network design

I'm trying to implement a multi-state, multi-state client application, and you have some questions about creating network / streaming projects. The problem I'm currently facing is messaging between the communication layer and the logical layer.

The server processes several clients, each of which can be active in several "channels", where each channel has several stages and can have several clients operating in it. Think about it with something similar to a multi-room chat program.

I have already implemented receiving messages on the server side. Each client has its own stream, which blocks the reading of data and decodes them into a message. Now how to proceed? In my presentation, each channel should also have its own stream in order to easily maintain its state. I could use BlockingQueue to exchange received messages with a channel stream that blocks waiting for new messages in this queue.

But then how to send messages to clients? The logic in the channel will process the message and create some messages for sending to one / several / all clients. Is it safe to use a channel stream to write directly to a socket? Or should I use another BlockingQueue to pass messages to the client handler thread? But how to wake him up, since he is waiting for the socket to read? Or should I use a separate send stream for each client or even a separate send-socket?

BTW: I know that I could use existing libraries for the network layer, but I want to do this from scratch on simple sockets.

+4
source share
2 answers

Place the message sending method on the communication object that wraps the socket. Synchronize this method to immediately call only one thread. Then it does not matter how many threads this method calls. Each message is sent only one at a time. You also do not need to disturb the thread that blocks reading. This sending method will be fast enough that you do not need to worry about blocking other threads when sending a stream.

As long as the channel has a link to communication objects for each connected client, it can send messages and not worry about it.

If this has ever caused problems, you can always modify this message to send the object to be sent. Then you can have a specific send stream to block the queue and write the contents to the socket. But in my experience this is not needed.

+1
source

What about the mechanism of events? When you are ready to process the request and there is data for the client, just send it with an event for the client socket handler thread. because the transfer from the client is completed, you can send the response normally - if I think correctly.

-1
source

Source: https://habr.com/ru/post/1337943/


All Articles