HTML5 WebSocket long connection

Achieve a long connection HTML5 WebSocket

First introduce WebSocket

The concept of WebSocket

  • HTML5 WebSocket is a protocol provided by the start of full-duplex communication over a single TCP connection.

  • WebSocket enables exchange of data between the client and the server easier, allowing the server actively push data to the client. In the WebSocket API, the browser and the server only needs to complete a handshake, you can directly create a persistent connection between the two, and two-way data transmission.

  • In the WebSocket API, the browser and the server just need to do a handshake of action, and then, on the formation of a fast-track between the browser and the server. You can transfer data directly between each other.

The advantage WebSocket

Many sites in order to achieve push technology, the technology used is Ajax polling. Polling is in a specific time interval (e.g., every 1 second), issues an HTTP request to the server by the browser, and returns the latest data to the client browser by the server.

This traditional model brings obvious disadvantage that the browser requires constant request to the server, however, HTTP requests may contain a long head, which truly effective data may only be a small part, obviously this will waste a lot of bandwidth resources.

HTML5 WebSocket protocol definition, better able to save server resources and bandwidth, and can be more real-time communication.
Here Insert Picture Description
Sent to the browser via JavaScript WebSocket server request to establish a connection after the connection is established, the client and the server can directly exchange data via TCP connection.

When you get the Web Socket connection, you can send data to the server through the send () method, and to receive the data returned by the server onmessage event.

The following WebSocket API is used to create objects.

var Socket = new WebSocket(url, [protocol] );

The above code first parameter url, specify the URL connection. The second parameter is optional protocol, the sub-protocol specified acceptable.

WebSocket property

Here Insert Picture Description

WebSocket event

Here Insert Picture Description

WebSocket method

Here Insert Picture Description

WebSocket API usage steps:

WebSocket connection to the server and the client, this is a real-time link long connection, once the server and client to establish a two-way link,
the data can be pushed to the Socket client as long as the server address and port with a bound Socket establish contact, you can receive push data sent.

1. create a connection, a new object is WebSocket , as follows:

var host = "ws://echo.websocket.org/";
var socket=new WebSocket(host);
  • URL must start with the characters "ws", the remaining part can be used as an HTTP address as written.
  • The address does not use the HTTP protocol writing, because its properties as WebSocket URL;
  • URL must consist of four parts, namely a communication flag (WS), the host name (Host), port number (Port) and WebSocket Server.

2. The transmission data, after WebSocket object is to establish contact with the server, transmitting data using the following code:

socket.send(dataInfo);
  • objWs as WebSocket newly created objects
  • dataInfo parameters send () method is a character type, i.e. can only use the text data or converting text JSON object into a data format of content.

3. Receive data, the client add an event mechanism for receiving data sent by the server:

socket.onmessage=function(event){
    //弹出收到的信息
    alert(event.data);
    //其他代码
}
  • Data acquired by the content server sends the "data" attribute event callback object, the content may be a string or JSON object.

4. The state flag, the status value "readyState" attribute record WebSocket connection procedure by the subject.

WebSocket object connecting process, by detecting changes in the state of this flag, the server can get the state of the client is connected, and a connection state has the form of a status code back to the client.

5. Close the socket connection

socket.close();

The complete code is as follows:

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>WebSocket实例</title>
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               alert("您的浏览器支持 WebSocket!");       
               // 打开一个 web socket
               var ws = new WebSocket("ws://echo.websocket.org");
               ws.onopen = function()
               {
                  // Web Socket 已连接上,使用 send() 方法发送数据
                  ws.send("发送数据");
                  alert("数据发送中...");
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert("数据已接收...");
               };
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  alert("连接已关闭..."); 
               };
            }
            else
            {
               // 浏览器不支持 WebSocket
               alert("您的浏览器不支持 WebSocket!");
            }
         }
      </script>
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
   </body>
</html>

Note: As used herein, socket server http://www.websocket.org/ website.
Protocol address is: ws: //echo.websocket.org/

Published 102 original articles · won praise 252 · views 20000 +

Guess you like

Origin blog.csdn.net/low666/article/details/105015118