N
N
nikitafrolov1322020-03-29 19:14:57
PostgreSQL
nikitafrolov132, 2020-03-29 19:14:57

Creating Node.js and Socket.io Dialogs?

I have a simple chat with registration and authorization written in Node.js and Socket.io . At the moment, I have implemented only a general chat for all registered users. All messages and users are stored in PostgreSQL . Now I need to make private dialogs between two users.

So far I have come up with only one idea how this can be implemented. When going to a certain URL, for example: localhost:8080/im${id} and sending a message, a dialogue is created in the database in the "dialogues" table between two users, where the first interlocutor, the second interlocutor and the ID of the last message in this dialog are passed :

INSERT INTO "public"."dialogues"("first_user", "second_user", "last_message") VALUES('3', '5', '24') RETURNING "id", "first_user", "second_user", "last_message";


How can I get/find out the URL that the user went to and process this request? How do I handle the second user receiving a dialog/message via Socket.io? For each such dialogue, will I have to create a separate room or can I do it somehow differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
de1m, 2020-03-30
@nikitafrolov132

socket.io has rooms/namespaces . Can't they be used?
Or something like this (from the same page)
Client

socket.on('connect', function () {
  socket.emit('join', {email: [email protected]});
});

Server
io.on('connection', function (socket) {
   socket.on('join', function (data) {    
    socket.join(data.email);
  });
});

Sending a message from the server side
io.to('[email protected]').emit('message', {msg: 'hello world.'});

We receive from the client
socket.on("message", function(data) {
  alert(data.msg);
});

M
MagicMight, 2020-03-29
@MagicMight

You can store an array of {roomid, talkwith} objects in the connected user's socket object.
roomid stores the room identifier in the database, talkwith - a reference to the object of the interlocutor's socket.
When creating a room or sending a message to a specific chat, the interlocutor socket in the array of listened chats also needs to register a pair of {roomid, talkwith}, where talkwith will be a link to the dialogue initiator socket

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question