Application background
First, let's look at what is websocket. WebSocket is an important feature of HTML5, and its communication protocol realizes the browser-based remote socket, which realizes the browser and server full duplex communication (Full-duplex).
Before WebSocket, in order to achieve instant communication, the technology used is polling, at a specific time interval, the browser sends an HTTP request to the server, and then the server returns the latest data to the client's browser, so that the browser needs to constantly make requests to the server, Will consume a lot of bandwidth.
In the WebSocket API, browsers and servers only need to do a handshake, and then a fast channel is formed between the browser and the server. The data can be transmitted to each other directly between the two. It solves the problem of Web real-time, which has the following advantages over traditional http:
1) A Web client establishes only one TCP connection
2) WebSocket server can push (push) data to the Web client.
3) have more lightweight head, reduce the amount of data transfer
WebSocket principle
We can think of the WebSocket application as having two parts, a client and a server. A WebSocket object is instantiated on the client, such as:
WS = New WebSocket ("Ws://yourdomain:port/path");
The WebSocket object automatically parses the string, sends it to the specified server port, and then the client and the service side establish a handshake. The data format sent by the client is similar:
Get/echo http/1.1
Upgrade:websocket
Connection:upgrade
Host :
http://www.51wp7.com:8080
Origin :
http://www.51wp7.com
The information that the service side should return is:
http/1.1 101 Web Socket Protocol Handshake
Upgrade:websocket
Connection:upgrade
Websocket-origin :
http://www.51wp7.com
Websocket-location : ws://
Www.51wp7.com:8080/echo
After the client handshake succeeds, the OnOpen event of the Webscoket object is triggered, telling the client that the connection has been successfully established.
The client has a total of four events bound.
1) OnOpen trigger after establishing connection
2) OnMessage trigger when message is received
3) OnError triggered when an error occurs
4) trigger when onclose off connection
Preliminary study on WebSocket