With the help of node practices WebSocket, node practices WebSocket

Source: Internet
Author: User
Tags key string

With the help of node practices WebSocket, node practices WebSocket

I. WebSocketOverview

WebSocket protocol,It is based on TCP rather than HTTP.

As follows:

Ws: // 127.0.0.1 or wss: // 127.0.0.1 is a WebSocket request.

Note:WsWebSocketProtocol, wssIndicates encrypted WebSocketProtocol.

WebSocketThe advantage is that the server and the client can communicate with each other in real time. Unlike Ajax, the client can only initiate requests and the WebSocket is not subject to the same-origin policy. This is exactly the weakness of Ajax.

Okay. After learning about WebSocket, let's explore and implement a Demo step by step.

2. Customer Service tour

Because it is based on WebSocket, A WebSocket request must be initiated first at the Customer Service end.

As follows:

<! DOCTYPE html> Second,Use the callback function to listen to and process the corresponding events. There are four listening events in total:

 1,Onpen:Triggered when the request is successful

  2,Onclose:Triggered when the request is closed

  3,Onerror:Triggered when an error occurs during a request or connection

  4, OnMessage:Triggered when receiving messages sent by the server

In addition,When a request is sent, the created WebSocket instance has a status value readyState:

  1,0:Indicates that the connection is not established or is being connected;

 2,1:Indicates that the connection is successful;

 3,2:Indicates that the connection is being closed;

  4,3:Indicates that the connection is closed.

We add these four listening events to the demo.

As follows:

<! DOCTYPE html> In this listener event, you can add the trigger function as you wish.

As follows:

<! DOCTYPE html> 3. Create a server for node

Create a simple server with node to view the entire WebSocket process.

Because it is a WebSocket protocol, you need to introduce the ws module in node. Assume that the port number we listen to is 8080.

As follows:

// The ws module var WebSocketServer = require ('ws'). Server is required; // create a wss Server var wss = new WebSocketServer ({port: 8080 });EntireCode

Next,After the connection is successful, we need to send a few things to the Customer Service side, such as 'Hello world', and the event message when listening to the Customer Service side for sending information.

As follows:

 

// The ws module var WebSocketServer = require ('ws') is required '). server; var wss = new WebSocketServer ({port: 8080}); wss. on ('connection', function (ws) {ws. on ('message', function (message) {var obj = JSON. parse (message); console. log ('stored ed: % s', obj. time) ;}); ws. send ('Hello World') ;}); console. log ('running !! ');EntireCode
Iv. Run

Prerequisites:Because the ws module is introduced, we need to introduce the ws module: npm install ws

First,Run the simple server built by node (I stored it in D: WebSocket/server. js ).

As follows:

 

Next, run the client code and open the chrome Debugger:

 

Let's take a look at the node environment just now. We have:

Solid,They can communicate with each other.

Open the chrome debugger and check the WebSocket request as follows:

 

In RequestHeadersMedium, "Connection: Upgrade" indicates that the browser notifies the server. If yes, it can be upgraded to the websocket protocol. Origin is used to verify whether the browser domain name is within the permitted range of the server. The Sec-WebSocket-Key is used for the handshake protocol Key, which is a base64-encoded 16-byte random string. The Upgrade header indicates that the communication protocol is switched from HTTP/1.1 to the specified protocol.

In ResponseHeadersMedium, "Connection: Upgrade" notifies the browser that the Protocol needs to be changed. The Sec-WebSocket-Accept is the server following the Sec-WebSocket-Key string provided by the browser. Add the "258eafa5-e914-4710995ca-c5ab0dc85b11" string and then take the hash value of sha-1. The browser will verify this value to prove that the target server has responded to the webSocket request.

5. Expand reading

[1] Ruan Yifeng, WebSocket

[2] Divid Walsh, WebSocket and Socket. IO

[3] socket. io

[4] Writing WebSocket client applications

[5] WebSockets: A Guide

 

Related Article

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.