What does app.set('socketio', io) do? #4157
-
Environment socket.io: 4.3.1 After a I use this: import express from "express";
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
app.set('socketio', io); // <--------------- what does this do? Whereas this guide: https://socket.io/get-started/chat#integrating-socketio Uses this: const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server); And this guide: https://github.com/socketio/socket.io#in-conjunction-with-express Uses this: const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server); My question is: What does I can see it is not used in any of the other guides mentioned above (maybe it was in older versions?). I've looked at the docs, but I don't understand what it means: http://expressjs.com/en/api.html#app.set And there is some related discussion here: https://stackoverflow.com/a/31277123 Reference For reference, my {
"presets": [
[
"@babel/preset-env",
{
"targets":
{
"node": "current"
}
}
]
]
} And I run it on my server side file from babel app_es6.js --out-file app.js |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
app.post('/hello', (req, res) => {
app.get('socketio').emit('hello');
res.send('done');
}) |
Beta Was this translation helpful? Give feedback.
-
Thank you for answer, unfortunately I am still trying to understand. Does "retrieve it later" mean "retrieve it outside of the import express from "express";
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
app.set('socketio', io);
// io and socket work within the function...
io.on('connection', async (socket) => {
// emit data
socket.emit('heres_your_socket_id', socket.id);
// listen for data
socket.on('some_event', async (data) => { // do things } );
// sanity check - get all connected sockets
const socket_ids_set = await io.allSockets();
console.log("socket_ids_set is currently:");
console.log(socket_ids_set );
// join a room
socket.join(room);
// another sanity check - get all connected sockets within a room
const room_socket_ids_set = await io.of("/").in(room).allSockets();
console.log(`room_socket_ids_set in "${room}" is:`);
console.log(room_socket_ids_set);
});
/*
... but 'io' and 'socket' do not work outside of the function?
eg you can't do this here:
socket.emit()
io.emit()
therefore we need to use this outside the function?
app.get('socketio').emit('hello');
*/ Why can't we use |
Beta Was this translation helpful? Give feedback.
app.set('socketio', io)
stores the Socket.IO server so you can retrieve it later withapp.get('socketio')
. For example: