WebSocket Learning and Group chat implementation

Source: Internet
Author: User
Tags button type node server
The > ' WebSocket ' protocol enables full-duplex communication at the front and back end, replacing long-polling for wasted resources. On the basis of this protocol, the front-end data, the multi-data, real * * Real-time response can be realized. In the course of learning ' WebSocket ', a simplified version of Group chat was implemented, with detailed documentation of the process and code in this article. * * This article is from [Dong Jinxin's personal website] (GODBMW.COM/PASSAGE/38), reference, please specify the origin * *. * * See more knowledge, or technical exchange: please visit [' godbmw.com '] (godbmw.com/) **## 1 Overview # # # 1.1 WebSocket what is it? 1. Network communication Protocol 2 based on TCP protocol. Full Duplex Communication Protocol 3. There is no homologous limit of 4. can send text, binary data, etc. # # # 1.2 Why do I need WebSocket? People who understand computer network protocols should know that the HTTP protocol is a stateless, non-connected, one-way application-level protocol. It uses the request/response model. The communication request can only be initiated by the client and the server responds to the request. This communication model has one drawback: the HTTP protocol cannot implement the server to initiate the message to the client actively. Therefore, if the client wants to listen to server changes in real time, Ajax must be used for polling, inefficient, and wasteful of resources. And WebSocket can make the * * front and back end of the full duplex communication (both sides can send data to each other), is a true equality dialogue * *. # # 2 WebSocket Client Support ' HTML5 ' browser supports WebSocket protocol: ' ' Javascriptvar ws = new WebSocket (URL); Create a WebSocket object ' # # # 2.1 WebSocket Properties | Properties | Description | | ----------------- | --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------- || Ws.readystate | The read-only property readyState represents the connection state, which can be the following value: 0-Indicates that the connection has not been established. 1-Indicates that the connection is established and can communicate. 2-Indicates that the connection is shutting down. 3-Indicates that the connection hasClose or the connection cannot be opened. Ws.bufferedamount | The read-only property bufferedamount has been put into the queue waiting for transmission, but has not yet emitted UTF-8 text bytes. |### 2.2 WebSocket Method | Properties | Description | | ---------- | -------- || Ws.send () | Data Sending | | Ws.close () | Close Connection |### 2.3 Websocket Event | Properties | Description | | ------- | ------------ || Open | Connection Establishment Trigger | | message | triggering when communicating | | Error | Error triggering | | Close | Close Connection trigger |### 2.4 Code implementation Assuming we have the WebSocket service open on the local ' 8080 ' port, the following code can be implemented in the browser to communicate with the service: ' HTML ' # # 3 WebSocket server > About service-side implementation, depending on the technology selection, different libraries and packages can be selected. I'm using the ' WS ' Library of ' node ' to websocket the server. In [Nanyi's post] (http://www.ruanyifeng.com/blog/2017/05/websocket.html) referred to the ' Socket.io ' library, in the browser side of the writing is not compatible with the native API, accurately speaking, They have implemented a set of WebSocket themselves. Therefore, the front and back end should refer to the third-party library when used. * * This results in a code migration, a serious decline. * * In summary, the ' WS ' Library has the following advantages: 1. Good compatibility, compatible with browser native API2. Long-term maintenance, stable effect 3. Easy to use (see below) # # 4 Realization Group Chat # # # 4.1 Group chat Server implementation First, on the command line, install the ' WS ' Library: ' npm install WS--save ' now, using ' WS ' To implement a WebSocket servers listening to ' 8080 ' ports * * The explanation is in the code comment, at a glance * *: "' javascriptconst PORT = 8080; Monitor Port Const WebSocket = require ("WS"); Introduce WS library CONST WSS = new Websocket.server ({port:port}); Declares the WSS object/** * Sends a message to all clients except itself, implements the group chat function * @param {*} data to be sent @param {*} WS Client Connection object */wss.broadcasttoelse = function Broadcast (data, WS) {Wss.clients.forEach (function each (client) {if (client!== ws && Client.readystate = = = WEBSO Cket. OPEN) {client.send (data);}});};/ * Client access, triggering connection */wss.on ("Connection", function connection (WS, req) {Let IP = req.connection.remoteAddress;//Through RE Q Object can obtain client information, such as: ip,headers, etc. /* The client sends a message that triggers a msg */Ws.on ("message", function incoming (message) {ws.send (message);//sends a message to the client Wss.broadcasttoelse ( message, WS); Send messages to other clients to achieve group chat effect}); "# # # 4.2 Group chat client implementation in order to facilitate the writing, the introduction of the ' jquery ' and ' bootstrap ' these two libraries, only need to focus on the JS code. "' HTML <title>Group Chat</title> <textarea class="form-control" rows="30" disabled="" id="show-area"></textarea> Send ' # # # 4.3 Group chat effect first start our service-side code: ' Node Server.js '. Where ' server.js ' is the file where the service-side code is placed. Then we open the ' HTML ' code written 2 times, which is equivalent to opening 2 clients. To detect the group chat feature. [] (Raw.githubusercontent.com/dongyuanxin/markdown-static/master/javascript/websocket Learning and Group chat implementation/1.png) # # 5. Related Materials-concept explanation:-http://www.ruanyifeng.com/blog/2017/05/websocket.html-www.cnblogs.com/jingmoxukong/p/7755643.html-' WS ' Documentation: www.npmjs.com/package/ws** This article is from [Dong Jinxin's personal website] (GODBMW.COM/PASSAGE/38), reference, please specify the source * *. * * For more information or technical Exchange: please visit [' GODBMW '] (godbmw.com/) * *

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.