This article mainly introduces the simple implementation of WebSocket function by NodeJS, and analyzes the client-side and server-side operation skills of nodejs to implement WebSocket communication function based on specific examples. Friends in need can refer to the examples of this article
Describes the simple implementation of WebSocket function in NodeJS. Share it with everyone for your reference, the details are as follows:
We develop based onexpressandsocket.io. First we need to install the following packages
npm install --save express npm install --save socket.io
Server-side code:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.send('Welcome Realtime Server
'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on("disconnect", function() { console.log("a user go out"); }); socket.on("message", function(obj) { io.emit("message", obj); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
Client-side code
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use puppeteer to crack the sliding verification code of JiExperience
Bind dynamically generated tags in jquery Event (detailed tutorial)
How to change page color in JS (detailed tutorial)
The above is the detailed content of How to implement WebSocket function using NodeJS. For more information, please follow other related articles on the PHP Chinese website!