This article mainly introduces the method of node.js using websocket based on express. It analyzes the related settings and usage techniques of node.js based on express calling websocket based on the example. Friends who need it can refer to it. I hope it can help everyone.
I also searched for this effect for a long time, and the test was successful. Anyway, it was successful, let’s take a look.
First you need to install the socket.io module
npm install socket.io --save
Then open express's app.js and import the module. Add two lines
# below thevar app = express();
##
var server = require('http').Server(app); var io = require('socket.io')(server);
app.use(function(req, res, next){ res.io = io; next(); });
var port = 3000; app.set('port', port); server.listen(port);
io.on('connection', function (socket) { socket.emit('news', { hello: 'world1' }); socket.on('my other event', function (data) { console.log(data); }); });
var socket = io.connect("//localhost:3000"); socket.on('news', function (data) { console.log(data); alert(data); socket.emit('my other event', { my: 'data' }); });
router.get('/', function(req, res, next) { //只有当前页面可以获得 res.io.on('connection', function(socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function(data) { console.log(data); }); }); //所有页面都可以获得 var io = require("../app").io; io.emit("news",{hello:"myworld"}); res.render("pclogin.ejs", {}); });
About the solution to the problem that the external network of the WebSocket deployment server cannot be connected
About websocket in php Detailed introduction
nodejs+websocket completes a chat system function
The above is the detailed content of Detailed explanation of node.js using websocket based on express. For more information, please follow other related articles on the PHP Chinese website!