wetlip
wetlip

Reputation: 133

send data from server to client on server event with socket.io

i can send data with a string tag on the server with

   import io = require('socket.io');
   var sio = io.listen(server);
   sio.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });

outside socket i can send a string only

sio.sockets.emit( "keystroke");

is there a way to make the data emitting possible outside on 'connecting' and not only a string.

i want to send json data on an event serverside with the same tag eg 'news'

Upvotes: 2

Views: 1837

Answers (1)

jfriend00
jfriend00

Reputation: 707328

Sure, you just have to save the socket that you want to send to or use a chatroom that you can broadcast to. Here's what it looks like if you save the socket:

import io = require('socket.io');
var sio = io.listen(server);
var client;
sio.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
    client = socket;
});


// then, sometime later in response to some server-side event,
// you can send to that saved socket
client.emit("whatever", {yourData: someData, otherData: whatever});

Of course, you probably don't save the client socket in a variable the way it is shown here because you probably support many different clients. How exactly you should save it depends upon what you're trying to do. If multiple client want to register an interest in specific types of events, then the chat room capability built into socket.io can serve that purpose pretty nicely. Each client can request to join that chatroom with your own specific command, the server can put them in that chatroom and then, when the event occurs, you can just broadcast the data to the chatroom and it will be sent to all clients how have been put in the chatroom. Chatrooms are like saved lists of client sockets that the socket.io library manages for you.

If you had all the clients in the "events" chatrooom, then you can broadcast to all clients in that chatroom from the server like this:

io.to('events').emit("whateverMsg", {yourData: someData, otherData: whatever});

Upvotes: 1

Related Questions