C
C
coelho2016-03-25 02:26:58
Java
coelho, 2016-03-25 02:26:58

Handling streams on messenger server?

For a student project, I am developing a kind of messenger, the connection is through sockets. What is the best way to handle streams on the server? So far, there are two options:
1) When connecting, we throw each client into a separate thread, in which we work with the database during the entire connection, send messages to recipients, etc. But this approach will severely limit the number of concurrent users.
2) We create a thread pool for a limited number of threads, and process incoming messages there. But how in this case to send a message to the recipient, because we do not have an open socket with him? You can store the ip of the last connection in the database in the database, but this will not solve the problem with the lack of an open socket.
What would be the best way to organize all this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nirvimel, 2016-03-25
@coelho

The number of threads is not equal to the number of open sockets. In no case should you spend a separate stream on each connection. But it is not necessary to close the socket synchronously after processing the connection. Socket - just the value of the cell of the array (or map) will be taken and used when needed in any thread (work with a specific socket, of course, must be wrapped in the appropriate sync block). The only thing you should not forget about is KeepAlive pings (a separate pool of threads and a timer for them, for example), which provide two tasks at once: 1) help keep an inactive connection (smart routers like to close "dead" connections, and the client, depending from the implementation, can do the same). 2) clear the list of sockets from really dead ones.

R
res2001, 2016-03-25
@res2001

You can implement without threads, consider an asynchronous approach to handling connections. Like in nginx.
It will be interesting!

K
Konstantin Malyarov, 2016-03-25
@Konstantin18ko

If there are no conditions for student work, then we take JMS technology and do not reinvent the wheel.
Otherwise, your work will not be perfect.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question