D
D
Denis11112018-10-12 14:48:42
Node.js
Denis1111, 2018-10-12 14:48:42

How to make private messages on node js socket.io?

How to make private messages on node js socket.io?
There is a server, there is an authorization and a chat. Authorization is related to the chat.
Question: How is it not a general chat, but a private one?!?!? I didn't find anything on the Internet.
If possible, please provide some simple code or explain how it works.
I know how to send a message to a specific socket, by socket.id, but I don’t know how to use it and I don’t understand at all what to do with it, how to get it from the client and forward the message to him by its id. Help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Gerasimov, 2018-10-14
@Omashu

From the client side, pass a jwt token or a cookie (session). On the side of the node, write a middleware that, at the time of connection, will process this data and record the client.
For example, like this:

const io = socket();

io.use(async (socket, next) => {
  try {
    const { token } = socket.handshake.query;
    const data = await verify(token);
    socket.request.user = data;
    return next();
  } catch (err) {
    // ignore
    return next();
  }
})

Now you have user data in the connection object and you can send a message to a specific user by finding his connection.

A
artkhromov, 2018-10-12
@artkhromov

The easiest way to learn when you already know the basics is by studying open source projects
Easier:
Let's Chat sdelements.github.io/lets-chat
node-chat https://github.com/IgorAntun/node-chat
Harder:
Rocket Chat https://rocket.chat ( https://github.com/RocketChat)
+ Socket.io itself has a good tutorial as far as I remember and Feathers.js (realtime framework based on Express)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question