1

I am trying to develop an Instant messenger using WebSocket.

I have multiple instances of my servers running (say server1 , server2). Two users(say userA , userB) who wants to chat with each other. But connected to different servers. UserA to Server1 and UserB to server2

Need some suggestion on how to implement

Approach 1 :

Initially, I was thinking to have a centralized database, which stores the connections(whenever a connection is established). Something like (simplest table structure)

User_id , Socket_object  

Let's say userA is sending a message to userB.

So that I will fetch the socket object of the receiver(userB) from the database and send the message directly to UserB . But later I came to know ServerSocket object is not serializable in Java.

Approach 2:

Whenever a connection is established, the server which accepted the connection can save the below details in a table.

 user_id , server_name , server_port 

when some server receives a message. It gets the destination server detail from the table and make a connection(probably HTTP, since we don't need persistence) to that destination server and push the message. Then the destination server passes the information to the respective user.

How to proceed with Implementation? Is there any other better way to implement it.

Please do not suggest some third-party libraries.

Jeevi
  • 149
  • 4
  • What's the problem with third party libraries? Redis is popular with storing session state, message queue probably more appropriate to route messages to another server once you have detected which server the other client is on – Martin K Feb 17 '20 at 21:34
  • You say you want to use websockets but you talk about Java Sockets. A Java Socket is a TCP Socket, not a websocket. Are you actually using websockets? You aren't trying to hand-roll a websocket handler, are you? That's highly inadvisable. – JimmyJames Feb 17 '20 at 22:14

1 Answers1

1

the second approach sound better than the first 1 although i wont use it. dealing with a data base when loading a lot of messages on your servers might be time consuming.

the best solution for this problem is an in memory data base such as Redis that implement's the publish-subscribe.

it will save you a lot of developing time and will perform better.

if you really want to implement something yourself i will suggest to develop a load balancer in front of these servers.

whenever a user want to connect it will navigate his message to some server and keep that it's connected to server X with some data structure.

it will be in charge of the book keeping and will navigate each message to the relevant server.

when some server will get a message from user X to user Y on another server it will send it to the load balancer(or whatever you want to call it) that will route the message to the correct server.

i think that in memory mapping between the user and the server it's connected to will be best to chat instead of database.

Dev93
  • 21
  • 4