Reputation: 157
I am fairly new to using Node. I have created a project that uses Express and Socket.IO. I want to split my code up into multiple JavaScript files, so I created some modules. However, Socket.IO doesn't seem to do anything when written anywhere besides the main file.
I created a stripped-down version of what I am wanting to do. Here is the code:
package.json
{
"name": "playground",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
index.js (main)
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var world = require('./world.js');
var portNumber = 8086;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, () => {
console.log('Listening on port ' + portNumber);
});
world.js (module)
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
// Does nothing unless used in index.js
io.on('connection', (socket) => {
console.log('sending message');
socket.emit('foo', 'Hello world.');
});
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<h1>Hello World</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('foo', (message) => {
console.log(message);
});
</script>
</body>
</html>
When the following code is put inside index.js:
io.on('connection', (socket) => {
console.log('sending message');
socket.emit('foo', 'Hello world.');
});
Everything works fine; I can pass information to the client. However, when I put the same block of code in world.js, it does nothing.
Why does nothing happen when trying to use Socket.IO in another module, and what do I need to do to get it to work?
Upvotes: 0
Views: 450
Reputation: 108796
Your http server, the one you created in index.js, gets used by your socket.io server. If you don't tell your socket.io server about your http server, socket.io cannot do anything useful.
In index.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
...
http.listen(portNumber, () => {
console.log('Listening on port ' + portNumber);
});
So, if you want to put your socket.io stuff in a js module, you need to figure out how to pass that http
item to that module.
Do something like this in world.js
const SocketServer = require('socket.io')
function start (http) {
const io = new SocketServer(http)
io.on('connection', (socket) => {
console.log('sending message');
socket.emit('foo', 'Hello world.')
return io
})
module.exports = {start}
Then in your index.js do this.
var world = require('./world.js')
world.start(http)
and you'll pass along the necessary server item at http to your module.
Upvotes: 0