[This article is original, if reproduced, please indicate the source http://blog.csdn.net/yl02520/article/]
WebSocket is a new communication protocol HTML5, the current popular browsers support this protocol, such as Chrome,safari,firefox,opera,ie, and so on, the Protocol to support the earliest should be chrome, Since the CHROME12 has started to support, as the draft protocol changes, the implementation of the Protocol is constantly updated by the various browsers. The agreement is still a draft, did not become a standard, but the standard should only be a matter of time, from the proposed WebSocket draft to now has more than 10 versions, the latest is version 17, the corresponding protocol version number 13, the current support for the protocol is the most perfect browser is chrome, After all, the WebSocket draft Agreement is also published by Google.
1. WebSocket API Introduction
First look at a simple JavaScript code that calls the WebSockets API.
var ws = new WebSocket ("ws://echo.websocket.org");
Ws.onopen = function () {ws.send ("test!");
Ws.onmessage = function (evt) {console.log (evt.data); Ws.close ();};
Ws.onclose = function (evt) {console.log ("websocketclosed!");
Ws.onerror = function (evt) {console.log ("websocketerror!");
This code has only 5 lines in total, and now gives a quick overview of the meaning of these 5 lines of code.
The first line of code is the request for a WebSocket object, which is the address of the server that needs to be connected, as with the HTTP protocol using the http://, the WebSocket protocol URL uses the ws://, and the other secure WebSocket protocol uses wss:// Beginning.
The second line to the fifth behavior WebSocket object registers the processing function of the message, the WebSocket object supports four messages OnOpen, OnMessage, OnClose and OnError, when the browser and Websocketserver connections succeed , a onopen message is triggered, and if the connection fails, the sending, receiving data fails, or an error occurs processing the data, browser triggers the onerror message, and the Websocketserver message is triggered when the browser receives the data sent by OnMessage , the parameter evt contains the data transferred by the server, and the OnClose message is triggered when browser receives a close connection request sent by the Websocketserver side. We can see that all of the actions are triggered by messages, so that the UI is not blocked, allowing faster response times for the UI and a better user experience.