HTML5 WebSocket authoritative Guide to learning one (chapter II WebSocket API)

Source: Internet
Author: User

Two URL schemes of WebSocket protocol
Non-encrypted traffic between WS client and server
Encrypted traffic between the WSS client and server

WebSocket secure means that WebSocket connections using Transport Layer Security (SSL) use HTTPS security to secure HTTP connections

Constructors for 1.WebSocket

var ws = new WebSocket ("ws://www.websocket.org");

  

2.WebSocket Object Dispatch 4 different events open message error close
Handling method: Same as all webapi with on< event name > Handler Properties
A.websocket Event Open
Definition: Once the server corresponds to a websocket connection request, the Open event fires and establishes a connection. The callback function corresponding to the Open event is called OnOpen
Code:

var ws = new WebSocket ("ws://www.websocket.org"), Ws.onopen = function () {Console.log ("connect Success");};

Meaning: When the Open event is triggered WebSocket is ready to send and accept the data application to receive the Open event then it is determined that the WebSocket server successfully processed the connection request and agreed to communicate with it.

B.websocket Event Message
Definition: The message event is triggered when the messages are received, and the callback function corresponding to the event is onmessage
Code:

WS = New WebSocket ("ws://127.0.0.1:2346"); ws.onopen = function () {alert ("Connection succeeded");  Ws.send (' Tom '); Alert ("Send a string to the server: Tom"); Ws.onmessage = function (e) {alert ("message received from the server:" + e.data);};

  

C.websocket Event Error
Definition: The Error event is triggered in response to an unexpected failure. The callback function corresponding to the event is onerror
If you receive an error event, you can expect the close event to be triggered soon. The code and reason in the close event can sometimes tell you the origin of the error.
Code:

Ws.onerror = function (e) {cosole.log ("WebSocket Error:", e); Handleerrors (e);};

D.websocket Event Close
Definition: The Close event triggers the corresponding callback function when the WebSocket connection is closed to OnClose once the service terminates
Code:

Ws.onclose = function (e) {console.log ("Connection closed", e);};

3.Websocket There are two methods of Send () and close ()
A.websocket method: Send ()
Definition: Use the Send () method to send a message from the client to the server after sending one or more messages, you can keep the connection open, or call the Close () method to terminate the connection call the Send () method before calling the OnClose listener after calling the OnOpen monitor
Code:

Ws.send ("Hello Mark");


Note: The Send () method sends the data when the connection is open, if the connection is not available or if it is turned off an exception that throws an invalid connection state
To avoid attempting to send a message before the connection is opened

Capturing JS Exceptions

var ws = new WebSocket ("ws://120.77.245.130:2346"); try{    ws.send (' Tom ');} catch (e) {    alert (e);} JavaScript Error Object: Name: Error name Number: Error Description: Description Information message: Error message filename: Error occurred file stack: Call stack when an error occurred

  

The above example throws an exception because the connection has not been opened to wait for the OnOpen event to be triggered to send the first message on the newly constructed WebSocket

var ws = new WebSocket ("ws://120.77.245.130:2346"); Ws.onopen = function () {ws.send (' Tom ');}


B.websocket method:Close ()
Definition: Use the Close () method to close the WebSocket connection or terminate the connection attempt if the connection is closed, the method does nothing. After you call Close (), you cannot send any data on a websocket that has been closed
Parameter: Close (Param code,param reason)
Code numeric Status Codes reason a text string
Passing these two messages, you can pass the reason for the shutdown to the server
Code:

Ws.close ("closing normally");

Object characteristics of 4.Websocket
A. readyState Easy to understand WebSocket connection status
Code:


B. bufferedamount data on-line transmission rate WebSocket object can tell you the size of the cache
Bufferedamount attribute check has entered the queue, but the number of bytes not yet sent to the server
Code (using the Bufferamount feature to send updates every second, such as the network can not withstand this rate, it will make the appropriate adjustment):

var THRESHOLD = 10240;var ws = new WebSocket ("ws://120.77.245.130:2346/"); ws.onopen = function () {setinterval (function ()  {if (Ws.bufferedamount < THRESHOLD) {Ws.send (Getapplicationstate ()); }},1000)}

  

The Bufferedamount feature is useful for restricting the rate at which applications send data to the server, thus avoiding network saturation.

C. Protocol
Before the initial handshake, the null server did not select which protocol the client provided that the attribute is also a null value

5. Determine if the browser supports WebSocket

if (window. WebSocket) {console.log ("This browser support WebSocket");} else{Console.log ("This browser does not the support WebSocket");}

  

HTML5 WebSocket authoritative Guide to learning one (chapter II WebSocket API)

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.