简体   繁体   中英

Socket.io inside express routes

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM