Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io: send message to specific room (client side)

In socket.io, you usually use a specific syntax on the server side if you want to send a message to a specific room: io.to(room).emit('event', 'message');.

But how would a client (what I mean is the socket.io-related code running in a browser) indicate that a message should go to a specific room?

Is it common to just create something like this (of course the server has to evaluate it):

socket.emit('chat message', {room: 'abc', msg: 'hello there'}); 

Or does the socket.io client-side library offer a specific syntax for this purpose as well?

edit: to clarify, my suggestion from above seems to work, I'm just not sure if there's a better solution.

like image 945
alapeno Avatar asked May 25 '15 09:05

alapeno


People also ask

How do I send a message to a specific socket?

To send a message to the particular client, we are must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using, socket.broadcast.to('ID'). emit( 'send msg', {somedata : somedata_server} ); For example,user3 want to send a message to user1.

How many rooms can socket.io handle?

socket.io rooms are a lightweight data structure. They are simply an array of connections that are associated with that room. You can have as many as you want (within normal memory usage limits). There is no heavyweight thing that makes a room expensive in terms of resources.


1 Answers

You've pretty much figured it out. Only the server can emit to specific rooms, because it is only the server that is actually connected to multiple clients. In other words, clients aren't connected to each other — the client-side library only manages communications between that one client and the server. So, if you want your client app to instruct the server to emit a message to all clients connected to a given room… that's basic API design. You could emit a socket event, or just do a regular http call to a route on your server. Either way you'll be sending metadata about which room(s) the server should broadcast to. The former (emitting) is probably preferred however, because that way on the server side you can use socket.broadcast.to to emit to all clients in the room EXCEPT the socket that initiated the call (a pretty common use case).

like image 101
Gabriel L. Avatar answered Sep 30 '22 17:09

Gabriel L.