Muhammad Farooq
Muhammad Farooq

Reputation: 21

io.sockets.emit works but io.sockets.on doesn't

I have to use Socket.IO with ExpressJS route. I am able to emit an event to client but unable to listen to event emitted from client. This issue comes in case when I have to use socket with Express route.

My server.js looks like this: (here emit command works but io.sockets.on doesn't). I have checked issues with similar problems but still didn't get any clear answer.

var express = require('express');
var app = express();
var server = app.listen(3000);
var io = socketio(server);
app.set('socketio', io);
app.post('/deploy', function(request, response) {
  var io = request.app.get('socketio');
  var dapp = "some data";
  io.sockets.emit('deploy', dapp);
  io.sockets.on('deploy_result', (result) => {
    console.log(result);
  });
})

Upvotes: 1

Views: 1071

Answers (2)

laggingreflex
laggingreflex

Reputation: 34627

io.sockets.on (or io.on) won't let you listen to all events, it's just for "connection" event. You'll have to attach your listener to each socket in order to listen to all events, like this:

io.on('connection', function (socket) {
  socket.on('deploy_result', (result) => {
    console.log(result)
  })
})

Also it seems like you're trying to get an "acknowledgement" for an emit, in which case there already exists a better way - the acknowledgement callback, simply pass a callback method as an additional argument (after the data):

  • server.js

    io.on('connection', function (socket) {
      socket.emit('deploy', {some: 'data'}, function acknowledgement_callback (result) {
        console.log(result)
      })
    })
    
  • client.js

    socket.on('deploy', (data, acknowledgement_callback) => {
      // Do something with `data`
      // Then call the callback with any result:
      acknowledgement_callback('result')
      // This will fire the "acknowledgement_callback" above on server-side
    })
    

Upvotes: 1

chinazaike
chinazaike

Reputation: 517

You will need to install express and socket.io eg. in the directory where you have your files as you can see in your codes and then reference those links appropriately

I have updated your code so issue of express and socket will work. its now left for you to ensure that your application run as you like. here is the link on how to install express https://www.npmjs.com/package/express

var socket  = require( './socket.io' );
var express=require('./express');
var app=express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;

app.post('/deploy', function(request, response) {
  var io = request.app.get('socketio');
  var dapp="some data";
  io.sockets.emit('deploy',dapp);
  io.sockets.on('deploy_result', (result)=>{
    console.log(result);
  });
})

Upvotes: 0

Related Questions