a websocket
WebSocket is a new communication protocol HTML5, the current popular browser supports this protocol, such as Chrome,safrie,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 it should only be a matter of time before it becomes a standard.
1. 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.
2 Why is the WebSocket protocol introduced?
Browser already supports the HTTP protocol, why develop a new websocket protocol? We know that the HTTP protocol is a one-way network protocol, and after the connection is established, it only allows Browser/ua (useragent) to send the requested resource to webserver, webserver to return the corresponding data. and webserver can not actively push data to Browser/ua, originally so design HTTP protocol also has reason, assuming webserver can actively push data to Browser/ua, that Browser/ua is too vulnerable to attack, Some advertisers will also take the initiative to send some advertising information inadvertently forcibly transferred to the client, this can not be said to be a disaster. So what is the problem with a one-way HTTP protocol for today's web site or Web application development?
Let's take a look at a case, now suppose we want to develop a Web-based application to get the real-time data of the current Web server, such as the real-time stock market, the ticket number of tickets and so on, which requires the Browser/ua and webserver end of the repeated HTTP communication, Browser constantly sends a GET request to get the current real-time data. Here are a few common ways:
1. Polling
This way is through Browser/ua timed to send HTTP to the Web server get request, the server received the request, the latest data sent back to the client (Browser/ua), Browser/ua get the data, it is displayed, Then repeat the process on a regular basis. Although this can meet the requirements, but there are still some problems, such as the Web server in a certain period of time there is no updated data, but Browser/ua still need to send a regular GET request to ask, then the Web server will transfer the old data back, browser/ The UA shows the unchanged data, which obviously wastes network bandwidth and wastes CPU utilization. This can be mitigated if the period of the browser send GET request is larger, but it does not guarantee the real-time nature of the data in the Web application if the data is updated very quickly on the Web server side.
2. Long Polling
The above describes the problems encountered by polling, and now introduce longpolling, it is an improvement to polling.
Browser/ua send a GET request to the Web server, the Web server can do two things, first, if the server side has new data needs to be transmitted, immediately send the data back to the Browser/ua,browser/ua received data, immediately sent a GET request to the Web server; second, if there is no new data to be sent on the server side, unlike the polling method, the server does not send a response to Browser/ua immediately, but keeps the request in response to the request when new data arrives, and, of course, If the server's data is not updated for a long period of time, the GET request will time out, Browser/ua receive a timeout message, and then immediately send a new GET request to the server. Then loop through the process in turn.
This approach, although to some extent, reduces the network bandwidth and CPU utilization problems, but there are still defects, such as the assumption that the server side of the data update rate is faster, the server after transmitting a packet to browser must wait for the next get request of browser arrival, In order to pass the second updated packet to browser, so that the browser display real-time data the fastest time is 2xRTT (round-trip time), and in the case of network congestion, this should not be acceptable to the user. In addition, because HTTP packet header data is often large (usually more than 400 bytes), but the actual data required by the server is very small (sometimes only 10 bytes or so), such a packet on the network periodic transmission, it is inevitable that network bandwidth is a waste.
The above analysis shows that if the browser can have a new network protocol, can support the client and server side of the two-way communication, and the Protocol's head is not so large. WebSocket is on the stage with such a mission.
3 WebSocket Protocol
The websocket protocol is a two-way communication protocol that is based on TCP and transmits data over TCP as HTTP, but it differs from HTTP by a maximum of two points: 1. WebSocket is a two-way communication protocol, after establishing a connection, the WebSocket server and Browser/ua can actively send or receive data to each other, just like a socket, The difference is that WebSocket is a simple analog socket protocol based on Web, 2. WebSocket need to be connected via a handshake, similar to TCP It also requires a handshake connection between the client and server to communicate with each other after the connection is successful.
Here is a simple timing diagram to build the handshake:
Here is a brief explanation of the WebSocket handshake process.
When the Web application calls the new WebSocket (URL) interface, browser begins the process of establishing a handshake connection with the Webserver address as a URL.
1. Browser with the WebSocket server through a TCP three handshake to establish a connection, if the connection fails, then the subsequent procedure will not be executed, the Web application will receive an error message notification.
2. After TCP establishes the connection successfully, BROWSER/UA transmits the WebSocket supported version number through the HTTP protocol, the Word version number of the Protocol, the original address, the host address and so on some column fields to the server side.
For example:
Get/chat http/1.1
Host:server.example.com
Upgrade:websocket
Connection:upgrade
sec-websocket-key:dghlihnhbxbszsbub25jzq==
Origin:http://example.com
Sec-websocket-protocol:chat,superchat
Sec-websocket-version:13
3. After the WebSocket server receives the handshake request sent by Browser/ua, if the packet data and format are correct, the client and server side protocol version number matches, and so on, accepts this handshake connection, and gives the corresponding data reply, the same reply packet is also transmitted using HTTP protocol.
http/1.1 101 Switching protocols
Upgrade:websocket
Connection:upgrade
sec-websocket-accept:s3pplmbitxaq9kygzzhzrbk+xoo=
Sec-websocket-protocol:chat
4. Browser received the server reply to the packet, if the packet content, format is not a problem, it means that the connection is successful, triggering the OnOpen message, the web developer can at this time through the send interface to the server to send data. Otherwise, the handshake connection fails, and the Web application receives the ONERROR message and knows why the connection failed.
4 the relationship between WebSocket and Tcp,http
WebSocket is TCP-based like the HTTP protocol, so they are all reliable protocols, and the WebSocket send function that the web developer invokes is ultimately transmitted through the TCP system interface in the implementation of the browser. WebSocket and the HTTP protocol belong to the application layer protocol, so what is the relationship between them? The answer is yes, websocket in the handshake connection, the data is transmitted through the HTTP protocol, as we saw in the previous section of the "Get/chat http/1.1", where the use of only the HTTP protocol some simple fields. However, after the connection is established, the actual data transfer phase is not required to participate in the HTTP protocol.
The specific relationship can be consulted:
5 websocket server
if we want to build a Web server, we will have a lot of choices, there are many mature products in the market for our application, such as open-source Apache, after installation only simple configuration (or the default configuration) can work. But if you want to build a websocket server is not so easy, because WebSocket is a new communication protocol, is still a draft, not a standard, the market is not mature WebSocket server or library implementation WebSocket Protocol, We have to write our own code to parse and assemble websocket packets. To complete a WebSocket server, it is estimated that all people want to give up, fortunately, there are several relatively good open source libraries in the market for us to use, such as Pywebsocket,websocket-node, libwebsockets and so on, These library files have already implemented the encapsulation and parsing of websocket packets, and we can call these interfaces, which greatly reduces our workload. As
Here is a brief introduction to these open Source library files.
1. Pywebsocket
Pywebsocket uses the Python language to write, can be very good cross-platform, the expansion is also relatively simple, at present WebKit uses it to build WebSocket server to do layouttest.
We can get the source code through the following command
Svncheckouthttp://pywebsocket.googlecode.com/svn/trunk/pywebsocket-read-only
More detailed information can be obtained from http://code.google.com/p/pywebsocket/.
2. Websocket-node
Websocket-node is written in JavaScript, and this library is built on top of Nodejs, and for those familiar with JavaScript, it's a bit more popular with HTML5 and Web applications, Nodejs is also being widely watched.
We can get the source code from the link below
Https://github.com/Worlize/Websocket-Node
3. Libwebsockets
The libwebsockets is written in C + + languages and can be customized with greater force, and we can participate in programming from the start of TCP listening to the completion of the packet.
We can get the source code from the following command
Git clonegit://git.warmcat.com/libwebsockets
It is worth mentioning that: WebSocket can be shared with the HTTP listening port, that is, it can be a public port to complete the socket task.
Two Socket.io
N Ode.js provides an efficient service-side operating environment, but due to the browser-side support for HTML5, in order to be compatible with all browsers, to provide a superior real-time user experience, and to provide programmers with a client-to-server consistent programming experience, so Socket.io was born. Socket.io encapsulates the WebSocket and polling (Polling) mechanisms and other real-time communication methods into a common interface, and implements the corresponding code for these real-time mechanisms on the server side. In other words, WebSocket is only a subset of the Socket.io implementation of real-time communication. So, Socket.io have implemented the communication mechanisms in the polling?
- Adobe®flash®socket
- AJAX Long Polling
- AJAX multipart streaming
- Forever Iframe
- JSONP Polling
Adobe®flash®socket Most PC browsers support the Socket mode, but is embedded in the browser through a third party, not within the specification, so it may be phased out, and most of the mobile browser does not support this mode.
AJAX Long polling This is a good understanding, all browsers support this way, is the timing of sending requests to the server, the disadvantage is that it will bring pressure on the server and the occurrence of information update is not timely phenomenon.
AJAX multipart streaming This is a multi-part flag that is supported on XMLHttpRequest objects using some browsers (such as Firefox). The AJAX request is sent to the server side and remains open (suspended), each time it needs to send a message to the client, it looks for a pending HTTP request response to the client, and all responses are written through a unified connection
var xhr = $.ajaxsettings.xhr (); Xhr.multipart =true; Xhr.open ('GET'Ajaxtrue); Xhr.onreadystatechange = function () { 4) {processevents ($.parsejson (Xhr.responsetext)); }};xhr.send (null);
The Forever iframe (persistent iframe) technique involves a hidden iframe tag placed on a page that has the SRC attribute pointing to the servlet path that returns the server-side event. Each time the event arrives, the servlet writes and refreshes a new script tag with JavaScript code inside it, and the contents of the IFRAME are appended to the script tag, and the contents of the tag are executed. The disadvantage of this approach is that the data is processed by the browser via HTML tags, so you have no way of knowing when the connection is broken, and the IFRAME tag is being phased out in the browser.
JSONP Polling JSONP Polling is basically the same as HTTP polling, but the difference is that JSONP can issue cross-domain requests, in detail, search for the contents of the query JSONP.
WebSocket and Socket.io Introduction