Nodejs implements WebSocket chat Based on the WS module, nodejswebsocket
This article describes how nodejs implements WebSocket chat Based on the WS module. We will share this with you for your reference. The details are as follows:
There are many WebSocket modules. I chose a simple module for implementation.
Tool: Sublime
Technology: Node. js reference module ws
The final result is as follows:
I was planning to create a network canvas. I forgot my work, so I simply implemented the group chat function.
There are no good introductions. There are too many online code cases. (You may encounter problems with the node import module)
Introduce the installation module:
Find the installation node directory and go to the npm directory and run cmd input.
npm install --save ws
The source file should be put in the npm directory and can be referenced (I am also a newbie, sorry)
Then execute node source file. js to access it;
Source code: Save it as a js file.
// Https://github.com/websockets/ws/blob/master/doc/ws.md#new-wsserveroptions-callbackvar WebSocketServer = require ('ws '). server, wss = new WebSocketServer ({port: 3000, // listener interface verifyClient: socketVerify // optional, verification connection function}); function socketVerify (info) {console. log (info. origin); console. log (info. req. t); console. log (info. secure); // console. log (info. origin); // var origin = info. origin. match (/^ (:?. + \: \/) ([^ \/] +)/); // If (origin. length> = 3 & origin [2] = "blog. luojia. me ") {// return true; // if it is from blog. luojia. me connection, accept //} // console. log ("connection", origin [2]); return true; // otherwise, the input info parameter will contain a lot of information about the connection. You can use the console here. log (info) to view and select how to verify the connection} // broadcast wss. broadcast = function broadcast (s, ws) {// console. log (ws); // debugger; wss. clients. forEach (function each (client) {// if (typeof client. user! = "Undefined") {if (s = 1) {client. send (ws. name + ":" + ws. msg);} if (s = 0) {client. send (ws + "Quit chatting room") ;}//}) ;}; // initialize wss. on ('connection', function (ws) {// console. log (ws. clients. session); // console. log ("online users", wss. clients. length); ws. send ('You are the first' + wss. clients. length + 'bit'); // send the message ws. on ('message', function (jsonStr, flags) {var obj = eval ('+ jsonStr +'); // console. log (obj); this. use R = obj; if (typeof this. user. msg! = "Undefined") {wss. broadcast (1, obj) ;}}); // exit the chat ws. on ('close', function (close) {try {wss. broadcast (0, this. user. name);} catch (e) {console. log ('refreshed page ');}});});
Html front-end source code:
<! DOCTYPE html>
There is not much verification in the chat, and the name can be changed at will,
Reference
Https://github.com/websockets/ws
Https://github.com/websockets/ws/blob/master/doc/ws.md
I hope this article will help you design nodejs programs.