Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use (socket.io)emit function outside of socket function - nodejs,express

I have the following code

var app = require('express')();
var http = require('http');
var server = http.createServer();
var socket = require('socket.io');
var io = socket.listen( server );

io.sockets.on('connection', function(socket) {
  console.log('socket connected');
  socket.broadcast.emit('newUser', 'New User Joined, Say Hi :D');

  socket.on('serverEmit',function(msg) {
    console.log('works');
  });

  socket.on('chatMessage', function(msg) {
    io.emit('server_emit', msg);
    console.log(msg);
  });
});

server.listen(3500, function() {
  console.log('listening on *:3500');
});

So my question is how to add an emit function outside of this socket connection. For example, if I have a get request like below

app.get('/link',function(req,res) {
  io.sockets.emit('trigger','triggered'); // Process I want to make
});

Thanks in advance.

like image 279
Deepak M Avatar asked Aug 01 '17 10:08

Deepak M


People also ask

Can you use Socket.IO with Express?

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.

What is difference between Socket on and Socket emit?

socket. emit - This method is responsible for sending messages. socket. on - This method is responsible for listening for incoming messages.


1 Answers

You almost had it:

it's io.emit('trigger','triggered');

And if you need to emit to a namespace you can do:

const namespace = io.of("name_of_your_namespace");
namespace.emit('trigger','triggered');
like image 166
Alexandre Senges Avatar answered Oct 16 '22 23:10

Alexandre Senges