WebSockets Study Notes (i)

Source: Internet
Author: User
Tags event listener

WebSocket is a network technology that HTML5 started to provide full duplex communication between the browser and the server. The WebSocket communication protocol was established as the standard RFC 6455,websocketapi by the IETF in 2011.

In the WebSocket API, the browser and server 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. (Wikipedia)

Background

Today, many Web sites are polled for the technology they use to implement push technology. Polling is at a specific time interval (such as every 1 seconds), the browser sends an HTTP request to the server, and then the server returns the latest data to the client's browser. This traditional pattern brings with it the obvious drawback that the browser needs to constantly make requests to the server, but the header of the HTTP request is very long, and the data contained in it may be a small value, which consumes a lot of bandwidth and server resources.

and the newer technology to do the polling effect is comet, using Ajax. However, although this technology can achieve two-way communication, but still need to make requests, and in comet, the widespread use of long links, which also consumes a lot of server bandwidth and resources.

In the face of this situation, HTML5 defines the WebSocket protocol, which can better save the server resources and bandwidth and achieve real-time communication.

Advantages Header

The header information exchanged between the server and the client is small, about 2 bytes. (Previous version)

Server Push

The server can proactively transmit data to the client. (Imagine, if the server will start in the morning and send the data to those clients who want to receive without having to establish some connection ports in advance, this is a wonderful thing!) Welcome to the world of push technology! )

Step three: Start creating the Client

Below to create the basic template, this is my client.php file:

<! Doctype html>   

We've created a basic template: A chat log container, an Input entry box, and a disconnected button.

Add some CSS

No fancy code, just dealing with the style of the label.

Body {font-family:arial, Helvetica, Sans-serif;      } #container {border:5px solid grey;      width:800px;      margin:0 Auto;  padding:10px;      } #chatLog {padding:5px;  BORDER:1PX solid black;  } #chatLog p {margin:0;  }. Event {color: #999;      }. warning{Font-weight:bold;  Color: #CCC; }
WebSocket Events

First let's try and understand the concept of the WebSocket event:

WebSocket Event:
We will use three WebSocket events:
OnOpen: When the interface is open
OnMessage: When a message is received
OnClose: When the interface is closed

How do we do that?
First create the WebSocket object

The server listening port needs to be changed to 8000var socket = new WebSocket ("ws://localhost:8000/socket/server/startdaemon.php")

Then detect the event as follows

Socket.onopen = function () {alert ("Socket has been opened!"); }

This is done when we receive the message:

Socket.onmessage = function (msg) {alert (msg);//awesome! }

But we try to avoid using alert, and now we can integrate what we've learned into the client page.

Javascript

First we put the code in the jquery document.ready function, and then we also check whether the user's browser supports WebSocket. If not, we'll add a link to the Chrome browser page.

$ (document). Ready (function ()  {      if (! () WebSocket " in window)" {          $ (' #chatLog,  input, button,  #examples '). FadeOut ("Fast");           $ (' <p>Oh no, you need a browser that supports  websockets. how about <a href= "Http://www.google.com/chrome" >google chrome</ A>?</p> '). AppendTo (' #container ');      }else{         //The user has WebSockets         connect ();         function connect () {           //the connect function code is below         }  });

As you can see, if the user's browser supports WebSocket, we will execute the Connect () function. Here is the core feature, and we'll start creating open, close, and receive events.

We will define the URL on our server.

var socket; var host = "ws://localhost:8000/socket/server/startdaemon.php";

You may find that there is no HTTP in the URL? Well, yes, it's a websocket URL that uses a different protocol. Here is the URL decomposition diagram:

Let's continue with the Connect () function, where we put the code into the Try/catch block, so we can let the user know if there is a problem with the code. We create the WebSocket and pass the information to the message () function, which is then explained. We create our OnOpen, onmessage, and OnClose functions. It is important to note that we provide the user with the port status, which is not required, but we put it in the main for the convenience of debugging.

connecting = 0
OPEN = 1
CLOSED = 2

Function connect () {      try{         var socket;      var host =  "Ws://localhost:8000/ socket/server/startdaemon.php ";      var socket = new  WebSocket (host);             message (' <p  Class= "event" >Socket Status:  ' +socket.readystate ";             socket.onopen = function () {                message (' <p class= ' "event" >Socket Status:  ' +socket.readystate+ '   (open) ');          }             socket.onmessage = function (msg) {                 message (' <p class= ' "message" >Received:  ' + Msg.data);          }             socket.onclose = function () {                message (' <p class= ' event ' >Socket Status:   ' +socket.readystate+ '   (Closed) ');           }                     } catch (Exception) {           message (' <p >error ' +exception);       }  }

The message () function is simple, and it fills in the chat log container The text we want to display to the user. We create the appropriate class for the paragraph (<p>) tag in the socket event function, and we have only one paragraph end tag in the message function.

Function Message (msg) {$ (' #chatLog '). Append (msg+ ' </p> '); }
The current results

If you've done it step by step in the tutorial above, well, we've created the Html/css template, created and established a websocket connection, and kept the user's progress updated by creating a connection.

Seventh Step: Send data

Now that we have the submit button, we also need to listen to the user press the keyboard event and run the Send function, and the following ' 13′ is the ASCII code for the ENTER key.

$ (' #text '). KeyPress (function (event) {if (Event.keycode = = ') {send (); }  });

Here is the Send () function:

function Send () {var text = $ (' #text '). Val ();          if (text== "") {message (' <p class= "Warning" >please enter a message ');      return;          } try{socket.send (text); Message (' <p class= ' event ' >sent: ' +text '} catch (Exception) {message (' <p class= ' warning ' > Error: ' + E      Xception);    } $ (' #text '). Val (""); }

Below we need to:

Socket.send ();


The extra code does the following: Detects if the user has entered nothing but still clicks back, empties the input box, and executes the message () function.

Close socket

Closing the socket operation is fairly straightforward, and adding the Click event Listener for the Disconnect button is OK.

$ (' #disconnect '). Click (function () {socket.close (); });
Full JavaScript code
$ (document). Ready (function ()  {      if (! () WebSocket " in window)" {    $ (' #chatLog, input, button,  #examples ') ). FadeOut ("fast");     $ (' <p>Oh no, you need a browser  that supports websockets. how about <a href= "Http://www.google.com/chrome" >Google Chrome</a>?</p> '). AppendTo (' #container ');    }else{         //The user has WebSockets           connect ();           Function connect () {            var  socket;            var host =  "ws:/ /localhost:8000/socket/server/startdaemon.php ";               try{                 var socket = new websocket ( Host);                   message (' <p class= ' event >Socket Status:  ' +socket.readystate ');                   socket.onopen =  function () {                    message (' <p class= ' "event" >Socket Status:  ' +socket.readystate+ '   (Open) ');                 }                   socket.onmessage =&nbsP;function (msg) {                    message (' <p class= ' message >Received:  ' +msg.data ');                 }                   socket.onclose =  function () {                   message (' <p class= ' "event" >Socket Status:  ' +socket.readystate+ '   (Closed) ' );                }                         } catch (Exception) {                messAge (' <p>error ' +exception);             }               function send () {                 var text  = $ (' #text '). Val ();                   if (text== "") {                     message (' <p class= ' Warning ">Please enter  a message ');                     return ;                 }                 try{                     socket.send (text);                     message (' <p class= ' event >Sent:  ' +text ')                    } catch ( Exception) {                    message (' <p class= ' Warning > ');                 }                 $ (' #text '). Val ("");             }               Function message (msg) {              $ (' #chatLog '). Append (msg+ ' < /p> ');            }               $ (' #text '). KeyPress (function)  {                 if  ( event.keycode ==  ')  {                   send ();                 }            } );                  $ (' # Disconnect '). Click (function () {                socket.close ();             });           }//End connect      }//End else     });


WebSockets Study Notes (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.