What are the best practices for implementing Socket.io?

Asked

Viewed 75 times

4

I am starting my studies on Socket.io, precisely in my project involving the technologies of Vue/quasar, and I would like to understand how the logic behind these following fundamentals unfolds:

  1. How do I get a user to chat with other users? (I sign in as user X, but I want to chat with users Z and Y individually, X with Y, X with Z, but not X with Y and Z) [I believe using namespace and rescuing the ids from each socket, but what is the best JS practice for this?]

  2. The listing of who is connected and who is not, I pull them by connecting to the id of each connected user socket within an array?

  3. Within the call of the socket.on function, it is possible to pass a parameter or need to pass each socket.on with its due parameter?

I have already researched stackoverflow and some other sites, but either there are no answers that clarify these my doubts or they are so advanced that I still can’t get the idea yet. I thank you in advance for the attention in this great doubt of mine!

1 answer

0

First, you would need a variable with users connected to the server:

const users = {}

Then you need an id for each person when they enter:

In the client (the name variable can be a prompt or an input):

socket.emit('userConnected', { name: name })

socket.emit('userConnected', { reciver: reciverName, msg: input.value })

And on the server, which is receiving Emit:

io.on('connection', (socket)=>{
    socket.on('userConnected', (data)=>{
        users[data.name] = socket.id
    })
    socket.on('chat message', (data)=>{
        io.to(users[data.reciver]).emit('chat message', data.msg)
    })
})
  • took long to receive reply neh? kakakaka

Browser other questions tagged

You are not signed in. Login or sign up in order to post.