Introduction to HTML5 WebSocket

Source: Internet
Author: User
Tags dot net

Email: longsu2010 at yeah dot net

WebSocket is the main channel for my current company to obtain data and an important part of my work. Today, I saw my colleagues discuss this issue and there were a lot of interesting things, such as debugging errors by making WebSocket synchronous (WebSocket is asynchronous full-duplex communication, the standard is like this ), therefore, make a simple description of WebSocket. If you need it, you may make a detailed supplement later. Please follow my CSDN blog.


Simple Example:
Var socket = new WebSocket ('ws: // '+ host +': '+ port );
Socket. onmessage = function (evt ){

Console. log (evt. data );
};
Socket. onclose = function (){};
Socket. onopen = function (){

This. send ("sent content ");
};
Socket. onerror = function (err ){

Console. log (err); console. log (arguments );
};

// Method for sending information

Function sendMsg (){
If (socket & (websock. readyState = 1 )){
Socket. send ("sdf ");
} Else {
// Put it into the sending queue
// Create or recreate a connection
}
}

When AJAX is used to obtain data, XMLHTTPRequest objects (instances) are generally not reused (a new object is created every time). However, WebSocket connections can be reused, and there are many advantages for data reuse, for example, the principle of reducing server connections and saving connection creation time is not reused. Because of the reuse, only one WebSocket instance is generally created. To ensure the communication reliability, you must check whether the WebSocket connection is available (whether the server has proactively disconnected the connection) before sending information ), message can be sent only when it is available. It cannot be put into the sending queue. The readyState attribute of the WebSocket instance is used to check the status of the WebSocket instance, as described below.

ReadyState
0: corresponding to the constant CONNECTING, indicating that the connection is being created
1: The constant "OPEN" indicates that the connection is in the communication status.
2: corresponding constant CLOSING, indicating the connection is being disconnected
3: corresponding constant CLOSED, indicating the connection has been disconnected

Because WebSocket instance creation and information transmission are asynchronous, callback functions are involved, such as which function is called after the connection is created. The callback function handles are as follows:
Onopen: Which function is called after the connection is created corresponds to an open event. It is suitable to send the information in the queue to the server.
Onerror: when the connection itself encounters a problem, the corresponding error event is suitable for reconnecting.
Onclose: when the connection is closed, it corresponds to the close event, which is suitable for clearing resources.
Onmessage: when the server pushes information to the client, it corresponds to the message event.

The WebSocket instance provides the following methods:
Send: send information to the server. If readyState is 1, true is returned. Otherwise, false is returned.
Close: close the WebSocket connection.

The WebSocket instance publishes the following events:
Open: when the connection is created, and the readyState changes from 0 to 1.
Message: whenever information is pushed from the server to the client.
Error: when the connection itself encounters an error
Close: when the connection is closed.

You can use the addEventListener method of the WebSocket instance to subscribe to events, for example:
Var onmsg = function (){

Console. log (arguments)
};
Socket. addEventListener ("message", onmsg );
To cancel a subscription, you can use removeEventListener, for example:
Socket. removeEventListener ("message", onmsg );

Function socket. addEventListener ("message", onmsg); and socket. onopen = onmsg; is the same, the difference is that the former can add multiple callback functions, while the latter is a value assignment operation, always using the last value assigned.

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.