0

Is it possible to use socket.io inside an express route?

I want it to look like this:

Server

app.js:

app.get('/cool_page/',users.cool_page);

users.cool_page:

if (5>3){
 socket.emit('first_connection',"true statement");
}

Client:

socket.on('first_connection',function(data){
 if (data === "true statement"){
  console.log("success");
 }

So far it hadn't been working. I tried to envelope the users.cool_page in io.sockets.on("conection",function(socket){code...}), but that didn't work. I also redefined some variables inside the users.cool_page; like

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

but it still doesn't work: without really outputting any error.

I appreciate any help. Thanks.

Adam
  • 482
  • 4
  • 15
  • Best solution here: http://stackoverflow.com/questions/37559610/socket-io-emit-on-express-route/37560779#37560779 – mdv Jun 01 '16 at 14:28

2 Answers2

0

To do something like this you will need to link each socket to an express session using something like socket.io.connect

By itself, socket.io has no knowledge of express's sessions and vice-versa.

dc5
  • 12,341
  • 2
  • 35
  • 47
0

The short answer is yes you just need to make sure you bind the socket calls to the request using a middleware or request emulator. However the better answer here would be for you to leverage a framework such as expressio to implement this in a more robust fashion.

Kyle Campbell
  • 186
  • 1
  • 4