WebSocket+node. js Create an Web chat server for instant messaging

  • 2021-07-09 07:03:39
  • OfStack

This article example node. js to create instant messaging Web chat server, for your reference, the specific content is as follows

1. Use nodejs-websocket
nodejs-websocket is a backend library based on node. js to implement websocket protocol,
Connection: https://github.com/sitegui/nodejs-websocket.
(1) Installation
Install from the project directory via npm: npm install nodejs-websocket
(2) Create a server


 // Introduce nodejs-websocket
var ws = require( " nodejs-websocket " );
// Call createServer Method to create a server, and call back the conn Yes connection Example of 
var server = ws.create(function(conn){
  console.log( " New connection " );
  // Eavesdropping text Events, text Event is triggered whenever text type data is received from the server, and the argument of the callback function is the passed string 
  conn.on( " text " , function(str){
 console.log( " Received  "  + str);
  });
  // Eavesdropping close Event, which is triggered every time the connection is disconnected 
  conn.on( " close " , function(code, reason){
 console.log( " Connection closed " );
  })
}).listen(8888);

2. Client uses websocket
On the client side, you first need to instantiate an websocket object: ws = new WebSocket ("ws://localhost: 5000"); The parameter incoming format is ws://+ url, which is similar to http protocol prefix http://1. Next, you can monitor events and display data through one method built into websocket.
Here, the system 1 introduces each listening event: onopen is triggered when the server and the client establish a connection; onmessage triggers when the client receives the data sent by the server; onclose is triggered when the connection between the client and the server is closed; onerror triggers when a connection error occurs.

3. Use websocket + nodejs to realize online chat room
(1) html and css codes are omitted
(2) Client js:


oConnect.onclick=function(){
    ws=new WebSocket('ws://localhost:5000');
     ws.onopen=function(){
       oUl.innerHTML+="<li> Client is 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 Two types of data transfer are supported: text Type and binary Type, where 2 The binary data is sent and read through the stream mode 
*/
var app=require('http').createServer(handler); // To simplify the code, put the specific code created by the server into handler In a 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 readFile Method to read files 
  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 are successful in 8888 Port to render the corresponding html Interface 
//conn Is corresponding to connection Example of 
var server = ws.createServer(function(conn){
  console.log('new conneciton');
  // Eavesdropping text Event that is triggered whenever text is received 
  conn.on("text",function(str){
    broadcast(server,str);
  });
  // When any 1 Triggered when the terminal closes the connection, which is the output in the console connection closed
  conn.on("close",function(code,reason){
    console.log('connection closed');
  })
}).listen(5000);
// Pay attention to the listen Listening is the port of the server just opened, and the client sends messages here for processing 
 
function broadcast(server, msg) {
  //server.connections Yes 1 An array containing all connected clients 
  server.connections.forEach(function (conn) {
    //connection.sendText Method can send the specified content to the client, passing in 1 String 
    // Here is traversing every 1 Clients send content for it 
    conn.sendText(msg);
  })
}

 That's the article 

Related articles: