Home > Article > Web Front-end > Detailed explanation of node.js using websocket based on express
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();around line 12.
##
var server = require('http').Server(app); var io = require('socket.io')(server);Then add
app.use(function(req, res, next){ res.io = io; next(); });to more than 20 lines. Since I don’t like to start from www, so in app.js Added a few more lines of code to the second to last line at the bottom
var port = 3000; app.set('port', port); server.listen(port);This will start listening to port 3000In this way, the preparations are complete Completed, and then start the exampleUse the official sample code to test, you can write it directly into app.js
io.on('connection', function (socket) { socket.emit('news', { hello: 'world1' }); socket.on('my other event', function (data) { console.log(data); }); });The preparation of the server has been completed , first introduce the socket.js file into the client page
<script src='javascripts/socket.io-1.4.5.js'></script> var socket = io.connect("//localhost:3000"); socket.on('news', function (data) { console.log(data); alert(data); socket.emit('my other event', { my: 'data' }); });Then open the page and test itIf you want to send information from the server to only one page , you can write like this
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", {}); });Related recommendations:
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!