Meet HTML5 's WebSocket

Source: Internet
Author: User
Tags event listener learnboost

My favorite Web technology in the HTML5 specification is the WebSocket API that is rapidly becoming popular. WebSocket offers a popular technology to replace the AJAX technology we've been using for the past few years. This new API provides a way to effectively push messages to the server from the client using simple syntax. Let's take a look at HTML5 's websocket API: It can be used for client, server side. And there is an excellent third-party API called Socket.io.

First, what is the WebSocket API?

The WebSocket API is the next generation of client-server asynchronous communication methods. This communication replaces a single TCP socket, using the WS or WSS protocol, which can be used with any client and server program. WebSocket is currently standardized by the consortium. WebSocket has been supported by browsers such as Firefox 4, Chrome 4, Opera 10.70, and Safari 5.

The great thing about the WebSocket API is that servers and clients can push information to each other at any point within a given time frame. WebSocket is not limited to communicating in Ajax (or XHR), because Ajax technology requires client-initiated requests, and WebSocket servers and clients can push information to each other, xhr are constrained by domains, and WebSocket allows cross-domain communication.

Ajax is a clever thing to do without designing the way to use it. WebSocket is created for the specified target and is used for two-way push messages.

Second, the use of WebSocket API

Focus only on the client's API, because each server-side language has its own API. The following code snippet is to open a connection, create an event listener for the connection, disconnect, message time, send a message back to the server, close the connection.

//Create a Socket instancevarSocket =NewWebSocket (' ws://localhost:8080 '); //Open SocketSocket.onopen =function(event) {//send an initialization messageSocket.send (' I am the client and i\ ' m listening! '); //Listening MessagesSocket.onmessage =function(event) {Console.log (' Client received a message ', event);   }; //Monitor the closing of the socketSocket.onclose =function(event) {Console.log (' Client notified socket has closed ', event);   }; //close the socket ....  //socket.close ()};

Let's take a look at the initialization fragment above. The parameter Url,ws represents the WebSocket protocol. The OnOpen, OnClose, and OnMessage methods connect events to the socket instance. Each method provides an event to indicate the status of the socket. The

OnMessage event provides a data property that can contain the body part of the message. The body part of the message must be a string that can be serialized/deserialized to pass more data. The syntax of the

WebSocket is very simple, and using WebSockets is incredibly easy ... Unless the client does not support WebSocket. Internet Explorer does not currently support websocket communication. If your client does not support WebSocket communication, here are a few fallback scenarios for you to use: the

Flash technology  --flash can provide a simple replacement. The most obvious disadvantage of using Flash is that not all clients have Flash installed, and some clients, such as Iphone/ipad, do not support Flash. The

Ajax long-polling Technology  --used Ajax long-polling to simulate websocket in the industry for some time. It is a viable technology, but it does not optimize the information sent. In other words, it is a solution, but not the best technical solution.

What if the current browser, such as IE, does not support WebSocket, to provide WebSocket event handling, return transmission, and use a unified API on the server side? Fortunately, Guillermo Rauch created a socket.io technology.

Third, WebSocket

Socket.io with Socket.io is Rauch WebSocket created by Guillermo Api,guillermo Rauch is the chief technology officer of Learnboost Corporation and the chief Scientist of Learnboost Laboratory. Socket.io uses the detection function to determine whether a websocket connection is established, or an AJAX long-polling connection, or flash, etc. You can quickly create real-time applications. Socket.io also provides a NODEJS API that looks very much like the client API.
Establish client Socket.io

Socket.io can be downloaded from github and include socket.io.js files on the page:

<script src= "Http://cdn.socket.io/stable/socket.io.js" ></script>[/codeat this point, Socket.io is valid on this page and it's time to create the Socket: [Code]//Create a Socket.io instance to establish a connectionvarsocket=NewIo. Socket (' localhost ', {port:8080 }); Socket.connect (); //Add a connection listenerSocket.on (' Connect ',function() {Console.log (' Client have connected to the server! '); });//Add a connection listenerSocket.on (' message ',function(data) {Console.log (' Received a message from the server! ', data); });//add a listener to close the connectionSocket.on (' Disconnect ',function() {Console.log (' The client has disconnected! '); }); //send a message to the server via the socketfunctionsendmessagetoserver (message) {socket.send (message);}

Socket.io simplifies the WebSocket API and unifies the return shipping API. Transmission includes:
WebSocket
Flash Socket
AJAX long-polling
AJAX multipart streaming
Iframe
JSONP Polling

You can also set the second option for any of the Socket.io constructors, which includes the following options:

Port-Ports to be connected
Transports-An array that contains different transport types
Transportoptions-Objects used for the transfer of parameters with additional properties

Socket.io also provides common connections, disconnects, message events that are provided by the local WebSocket API. The socket also provides a way to encapsulate each event type.

Iv. joint development of Nodejs and Socket.io

Socket.io provides a server-side solution that allows unified client and server-side APIs. With node, you can create a typical HTTP server and then pass the instance of the server to Socket.io. From here, you create a connection, disconnect, and build a message listener, just like the client.

A simple server-side script looks like this:

//HTTP module required to start server and Socket.iovarhttp= require (' http '), io= require (' Socket.io ')); //start the server on port 8080varServer= Http.createserver (function(req, res) {//Send HTML headers and messageRes.writehead (200,{' content-type ': ' text/html ' }); Res.end (' ); }); Server.listen (8080); //Create a Socket.io instance and pass it to the servervarsocket=Io.listen (server);//Add a connection listenerSocket.on (' Connection ',function(client) {//Success! Start listening to incoming messages now.Client.on (' message ',function(event) {Console.log (' Received message from client! ', event);   }); Client.on (' Disconnect ',function() {clearinterval (interval); Console.log (' Server has disconnected '); }); });

You can run the server section, assuming that Nodejs is installed and executed from the command line:

Node Socket-server.js

Now the client and server can push messages back and forth! Within the Nodejs script, you can create a recurring message sender using simple javascript:

// Create a regular (every 5 seconds) send message to the client's transmitter var interval= setinterval (function() {   client.send (new  Date (). GetTime ( )); },5000);

The server side will push the message to the client every 5 seconds!

Five, Dojox. Sockets and Socket.io

The creator of Persevere Kris Zyp created Dojox.socket. Dojox. The socket encapsulates the WebSocket API in a way that is consistent with the Dojo library to use long-polling overrides when the client does not support WebSocket.

Here's how to use Dojox on the client. Sockets and examples of using Socket.io on the server side:

varargs, ws=typeofwebsocket!= ' undefined '; varsocket= Dojox.socket (args={Url:ws? '/socket.io/websocket ': '/socket.io/xhr-polling ', headers:{' Content-type ': ' application/x-www-urlencoded '}, Transport:function(args, message) {args.content= message;//Use url-encoding to send the message instead of a raw bodydojo.xhrpost (args); }; }); varsessionId; Socket.on (' Message ',function(){   if(!sessionId) {SessionId=message; Args.url+ = '/' +sessionId; }Else if(Message.substr (0, 3) = = ' ~h~ '){    //a Heartbeat  } });

Dojox.socket.Reconnect also creates an auto-reconnect when the socket loses its connection. Expect to include Dojox. Early release of the socket's dojo version 1.6.

Vi. practical applications and WebSocket resources

There are many practical applications of Websocke. WebSocket is ideal for most client-server asynchronous communications, and chatting in the browser is the most prominent application. WebSocket is used by most companies because of its high efficiency.

Ext.: http://www.itpub.net/thread-1373652-1-1.html


WebSocket Resources

Socket.io site: http://socket.io/
WebSocket's Wikipedia:http://en.wikipedia.org/wiki/websockets
Dojo websocket site: http://www.sitepen.com/blog/2010/10/31/dojo-websocket/

Meet HTML5 's WebSocket

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.