Nội dung bài viết
Video học lập trình mỗi ngày
To connect Socket.IO with Node.js using the MVC model, you can follow these steps:
Install the Socket.IO and Express.js packages using npm:
npm install socket.io express
Create an app.js file that initializes an Express.js app and sets up Socket.IO to listen on the same server:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
server.listen(3000);
Create a routes directory that contains your MVC route files, such as index.js, users.js, etc. Each route file should define the route handling logic for a specific part of your application. For example, the index.js route file might look like this:
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Socket.IO + Express.js + MVC' });
});
module.exports = router;
In the app.js
file, load the MVC routes and set up the Express.js app to use them:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// Load MVC routes
const index = require('./routes/index');
const users = require('./routes/users');
// Use MVC routes
app.use('/', index);
app.use('/users', users);
server.listen(3000);
To handle Socket.IO events, you can define event handlers in the app.js
file or in separate Socket.IO controller
files. For example, you could define a socket.js file that contains the following code:
module.exports = function(io) {
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('disconnect', function() {
console.log('A user disconnected');
});
socket.on('chat message', function(msg) {
io.emit('chat message', msg);
});
});
}
Then, in the app.js
file, you can load the socket.js file and pass the io object to it, allowing it to register event handlers:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// Load Socket.IO controller
const socketController = require('./socket')(io);
// Load MVC routes
const index = require('./routes/index');
const users = require('./routes/users');
// Use MVC routes
app.use('/', index);
app.use('/users', users);
server.listen(3000);
With this setup