To use socket.io
in an Express.js 4 application created with the Express generator, you’ll need to perform the following steps:
- Install the
socket.io
andsocket.io-client
packages:
npm install socket.io socket.io-client --save
- In the
/bin/www
file, set up thesocket.io
server:
// /bin/www
var app = require('../app');
var http = require('http');
var io = require('socket.io')();
var server = http.createServer(app);
io.attach(server);
server.listen(3000);
server.on('error', onError);
server.on('listening', onListening);
...
- In a separate file, such as
/routes/index.js
, set up thesocket.io
event listeners:
// /routes/index.js
var express = require('express');
var router = express.Router();
var io = require('socket.io-client');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
console.log('Connected to server');
});
socket.on('event', function(data) {
console.log('Received event:', data);
});
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
module.exports = router;
In this example, the socket.io-client
library is used to connect to the socket.io
server and listen for events. You can emit events from the client-side code by calling the emit
method on the socket
object, and you can handle those events on the server-side by listening to the socket
events.
Note that in this example, the socket.io
server is attached to the Express server created in the /bin/www
file, and the client-side socket.io
code is included in the /routes/index.js
file. You can structure your application as needed, but this example demonstrates one possible way to set up socket.io
in an Express.js 4 application.
+ There are no comments
Add yours