WebSocket is a new communication protocol HTML5, the current popular browser supports this protocol, such as Chrome,safari,firefox,opera,ie, and so on, the earliest support for the protocol should be Chrome, Since the CHROME12 has started to support, as the draft agreement changes, the implementation of the various browsers to the protocol is constantly updated. The agreement is still a draft, not a standard, but to become the standard should be only a matter of time, from the proposed websocket to now have more than 10 versions, the latest is version 17, the corresponding version number of the protocol is 13, the current support for the most comprehensive browser is chrome, after all The WebSocket Draft agreement is also published by Google.
1. Introduction to WebSocket API
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 is only 5 lines in total, and now briefly outlines the meaning of these 5 lines of code.
The first line of code is to request a WebSocket object, the parameter is the server-side address that needs to be connected, the same as the HTTP protocol use//start, the URL of the WebSocket protocol uses ws://beginning, and the other secure WebSocket protocol uses wss:// Beginning.
The second line to the fifth behavior WebSocket object Registration Message handler function, WebSocket object supports altogether four messages OnOpen, OnMessage, OnClose and OnError, when browser and Websocketserver are connected successfully , the OnOpen message is triggered, and if the connection fails, the send, receive data fails, or the processing data error occurs, browser triggers the onerror message, and when browser receives the data sent by Websocketserver, the onmessage message is triggered. , the parameter evt contains the data transmitted 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 actions are triggered by the message, so that the UI is not blocked, and the UI has a faster response time and a better user experience.
Introduction to the WebSocket Communication Protocol API