Search code examples
node.jschatprivate

NodeJS - Best way to handle private messaging?


I want to create a private message system using NodeJS and websockets. I was wondering what the best way is to create such system.

Is it better to create 1 nodeJS server and bind listen-event for each user, or should I create a unique port/server for each conversation between 2 users. i.e.

conversation 1 (user1 & user2): port 8080

conversation 2 (user2 & user3): port 8081

conversation 3 (user1 & user3): port 8082


Solution

  • Is it better to create 1 nodeJS server and bind listen-event for each user, or should I create a unique port/server for each conversation between 2 users. i.e.

    Neither.


    You can easily create a private conversation between two users with one server listening on one port and allowing users to connect to the server and then identify which other user they want to have a private conversation with.

    1. A user identifies themselves to the server with some sort of credential when they login and connect to the server. Your server then knows which user belongs to which connection.
    2. The server can then facilitate a private conversation between any two users by simply allowing userA to pass messages to userB and vice/versa, but not allowing anyone else access to those messages. No private server per user is needed. No custom port is needed. You do need some sort of user authentication service so you can know which user is which with some appropriate level of credibility.

    You can see some pieces of what you're asking about in this socket.io demo chat server.

    Here's a more detailed description for how this works:

    1. UserA connects to the server and identifies themselves.
    2. UserB connects to the server and identifies themselves.
    3. UserC connects to the server and identifies themselves.
    4. UserA sends a message to the server instructing the server to send a private message to userC.
    5. The server receives that message from UserA and forwards it on to UserC.
    6. UserC receives the private message from userA.
    7. The server does not store the message from UserA or ever send it to any other users (thus making it a private message).
    8. UserC can then respond to UserA using the same mechanism.

    Note: It is a requirement of pretty much any scheme that you have both user authentication and you have a user identifier. You will then also have to surface that in a user interface so that a given user can identify which currently connected user they wish to communicate with.