0

I really need help getting past this problem I'm facing with socket.io. Believe me, I've looked at just about every post on this topic...

App.js

const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('User Disconnected');
  });
  socket.on('example_message', (msg) => {
    console.log('message: ' + msg);
  });
});

app.set('socketio', io);

const port = process.env.PORT || 7777;
app.listen(port);
console.log(`Server listening at ${port}`);

module.exports = app;

Routes.js

const express = require('express');
const router = require('express-promise-router')();


router.route('/test-route')
    .put(TestController.testEmit);

module.exports = router;

TestController.js

module.exports = {

  testEmit: async (req, res, next) => {
    const io = req.app.get("socketio");
    console.log(io); // this ACTUALLY logs the entire socketio object!
    io.emit('example_message', 'abc'); // NOTHING HAPPENS
  }

}

Every time I reload my client, I see the "a user connected" in the terminal window. However, when I attempt to emit from the testEmit controller, nothing ends up happening.

Conner P
  • 1
  • 1
  • 4
  • Are you looking to broadcast a message to _all_ clients? Also, please show the client code setup to receive the message. – James Mar 05 '19 at 08:58
  • There is only one client meant to receive a message for this route. I haven't setup anything on the client side to receive the message yet, since I couldn't get the backend part working! – Conner P Mar 05 '19 at 09:09
  • if the part you are referring to that's not working is `io.emit` then that's because you have no client setup to receive the event. `socket.on` on the server will only listen for _client_ emits, not server ones. – James Mar 05 '19 at 10:20
  • So what in your opinion would be the best way to solve the following case: User submits data into form on client #1 -> data is stored in db using express route -> data gets combined with other data pulled from DB -> data is emitted to client #2? – Conner P Mar 05 '19 at 17:55
  • it all depends on how you determine which client needs to receive the message. Probably the most robust way would be to make use of a [room](https://socket.io/docs/rooms-and-namespaces/), this would continue work as your app scaled. `io.emit` will broadcast a message to _all_ connected sockets. – James Mar 07 '19 at 12:49
  • Possible duplicate of [How to send a message to a particular client with socket.io](https://stackoverflow.com/questions/17476294/how-to-send-a-message-to-a-particular-client-with-socket-io) - the accepted answer has quite a lot of limitations, prefer [this answer](https://stackoverflow.com/questions/17476294/how-to-send-a-message-to-a-particular-client-with-socket-io/17535099#17535099) – James Mar 07 '19 at 12:49

0 Answers0