9

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.

Deepak M
  • 849
  • 8
  • 17
  • Follow link for better socket.io practice [Link](https://stackoverflow.com/questions/9709912/separating-file-server-and-socket-io-logic-in-node-js) – Arunkumar Topagi Jan 02 '19 at 16:47
  • Follow link for better socket.io practice [Link](https://stackoverflow.com/questions/9709912/separating-file-server-and-socket-io-logic-in-node-js) – Arunkumar Topagi Jan 02 '19 at 16:48
  • Follow link for better socket.io practice [Link](https://stackoverflow.com/questions/9709912/separating-file-server-and-socket-io-logic-in-node-js) – Arunkumar Topagi Jan 02 '19 at 16:50

2 Answers2

3

You need to export your io first so that it can be reusable.

socket-setup.js

const socket = require("socket.io")

let _io;

const setIO = (server) => {
    _io = socket(server, {
        cors : {
          origin : "*",
          headers : {
            "Access-Control-Allow-Origin" : "*"
          }
        }
      })
      return _io
}

const getIO = () => {
    return _io
}

module.exports = {
    getIO,
    setIO
}

Then in your app entry file (index.js), setup your io.

const app = express()
const server = http.createServer(app)

let io = setIO(server)
io.on("connection", socket => {
 //Your job
})

Then wherever, e.g. message.js you want to emit event. You can use io like this.

const onMessageRecieved = () => {
    try {
        getIO().emit("hello", "Bye")
    } catch (error) {
        console.log(error);
    }
}

That's it. Enjoy.

Alok Prakash
  • 191
  • 1
  • 9
  • is it possible to put `io.on("connection", socket => { //Your job })` *outside* of `app.js` - and if so, how would you 'include' it in `app.js` after that? i'm doing a refactor and trying to clean up `app.js` as much as possible, i have a question with more context [here](https://stackoverflow.com/questions/70125739/how-to-include-mongodb-client-common-middleware-and-other-bits-and-pieces-wit). – user1063287 Nov 27 '21 at 04:25
  • is this the accepted answer? – AmandaConda Dec 05 '21 at 03:17
2

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');
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22