This article example node.js creates a web chat server for instant communication for your reference. The specific content is as follows
1. Use nodejs-websocket
nodejs-websocket is a backend library that implements the websocket protocol written based on node.js.
Connection: https://github.com/sitegui/nodejs-websocket.
(1) Installation
Install through npm in the project directory: npm install nodejs-websocket
(2) Create a server
//Introduce nodejs-websocketvar ws = require("nodejs-websocket"); //Call createServer method to create the server, and the conn in the callback function is an instance of the connection var server = ws.create(function(conn){ console.log("New connection"); // Listen to the text event, and the text event is triggered whenever text type data is received from the server, and the parameters of the callback function are the passed string conn.on("text", function(str){ console.log("Received " + str); }); // Listen to the close event, and trigger conn.on("close", function(code, reason){ console.log("Connection closed"); })}).listen(8888);2. The client uses websocket
On the client, you need to instantiate a websocket object: ws = new WebSocket("ws://localhost:5000"); the parameter passed in is ws://+url, which is the same as the http protocol prefix http://. Next, you can use some built-in methods of websocket to monitor events and display data.
Here we introduce each listening event: onopen triggers when the server and the client establish a connection; onmessage triggers when the client receives data sent by the server; onclose triggers when the client and the server's connection is closed; onerror triggers when the connection error occurs.
3. Use websocket + nodejs to implement online chat room
(1) HTML and css code omitted
(2) Client js:
oConnect.onclick=function(){ ws=new WebSocket('ws://localhost:5000'); ws.onopen=function(){ oUl.innerHTML+="<li>Client connected</li>"; } ws.onmessage=function(evt){ oUl.innerHTML+="<li>"+evt.data+"</li>"; } ws.onclose=function(){ oUl.innerHTML+="<li>Client disconnected</li>"; }; ws.onerror=function(evt){ oUl.innerHTML+="<li>"+evt.data+"</li>"; }; }; oSend.onclick=function(){ if(ws){ ws.send(oInput.value); } }(3) Server side js: /*websocket supports two types of data transmission: text type and binary type, where binary data is sent and read through the stream pattern*/var app=require('http').createServer(handler); //To simplify the code, put the server creation specific code into the handler function var ws=require('nodejs-websocket'); var fs=require('fs');app.listen(8888); function handler(req,res){ //__dirname returns the current directory where the file is located. Call the readFile method for file reading fs.readFile(__dirname+'/index.html',function(err,data){ if(err){ res.writeHead(500); return res.end('error '); } res.writeHead(200); res.end(data); });}//The above steps successfully render the corresponding html interface on port 8888//conn is an instance of the corresponding connection var server = ws.createServer(function(conn){ console.log('new connecton'); // Listen to the text event, and trigger conn.on("text",function(str){ whenever text is received broadcast(server,str); }); // When any end closes the connection, the connection is output in the console. Closed conn.on("close",function(code,reason){ console.log('connection closed'); })}).listen(5000); //Note that the listener here is the port of the server that was just opened. The client sends the message here to process the function broadcast(server, msg) { //server.connections is an array containing all connected clients.connections.forEach(function (conn) { //connection.sendText method can send the specified content to the client and pass in a string // Here is to traverse each client to send the content to it conn.sendText(msg); })}The above is this articleI hope that all the content of this is helpful to everyone’s learning, and I hope that everyone will support Wulin.com more.