To bring you to know the WebSocket in HTML5.

Source: Internet
Author: User
Tags event listener require socket learnboost

Understanding the WebSocket of HTML5

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

First, HTML5 in the WebSocket API is what dongdong?

The WebSocket API is the next-generation client-server asynchronous communication method. This communication replaces a single TCP socket and can be used with any client and server programs using the WS or WSS protocol. 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 time within a given timeframe. WebSocket is not limited to Ajax (or XHR) communication because Ajax technology requires a client to initiate a request, while WebSocket servers and clients can push information to each other; XHR is restricted by the domain, and websocket allows Cross-domain communication.

The smart thing about Ajax is that there is no way to design it. WebSocket is created for the specified target for bidirectional push messages.

The use of WebSocket APIs in HTML5

Focus only on the client API, because each server-side language has its own API. The following code fragment opens a connection, creates an event listener for the connection, disconnects, messages time, sends a message back to the server, and closes the connection.

The

code is as follows:


//Create a Socket instance


var socket = new WebSocket (' ws://localhost:8080 ');


//Open socket


Socket.onopen = function (event) {


//Send an initialization message


socket.send (' I am the client and I ' M listening! ');


//Listening message


socket.onmessage = function (event) {


Console.log (' Client received a message ', event);


};


//Listening for socket shutdown


socket.onclose = function (event) {


Console.log (' Client notified socket has closed ', event);


};


//Close socket ...


//socket.close ()


};

Let's take a look at the initialization fragment above. The parameter is URL,WS to represent the WebSocket protocol. The OnOpen, OnClose, and OnMessage methods connect events to the socket instance. Each method provides an event that represents the state of the socket.

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

WebSocket's syntax is very simple, and using WebSockets is incredibly easy ... Unless the client does not support WebSocket. IE browsers do not currently support WebSocket communications. If your client does not support WebSocket communications, here are a few backup scenarios for you to use:

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.

Ajax long-polling Technology-using AJAX long-polling to simulate WebSocket has been in the industry for some time. It is a viable technique, but it does not optimize the information sent. In other words, it is a solution, but not the best technology solution.

Because the current IE and other browsers do not support WebSocket, to provide WebSocket event processing, return transmission, using a unified API on the server side, then what to do? Fortunately, Guillermo Rauch created a socket.io technology.

Iii. the WebSocket with Socket.io

Socket.io is WebSocket Api,guillermo Rauch, Guillermo Rauch, the chief technical officer of the Learnboost company and the lead scientist of the Learnboost laboratory. Socket.io uses detection to determine whether to establish a websocket connection, or an Ajax long-polling connection, or Flash. 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 to include the Socket.io.js file in the page:

The

code is as follows:


<script src= "Http://cdn.socket.io/stable/socket.io.js" ></script>


At this point, Socket.io is valid on this page and it is time to create the Socket:

The

code is as follows:


//Create Socket.io instance, establish connection


var socket= new IO. Socket (' localhost ', {


port:8080


});


Socket.connect ();


//Add a connection listener


socket.on (' Connect ', function () {


Console.log (' Client has connected to the server! ');


});


//Add a connection listener


socket.on (' message ', function (data) {


Console.log (' Received a message from the server! ', data);


});


//Add a listener that closes the connection


socket.on (' Disconnect ', function () {


Console.log (' The client has disconnected! ');


});


//Send a message through the socket to the server


function sendmessagetoserver (message) {


socket.send (message);


}

Socket.io simplifies the WebSocket API and unifies the return shipping API. Transmissions include:

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, including the following options:

Port-Ports to be connected

Transports-An array that contains different transport types

Transportoptions-Objects used by the parameters of the transfer, with attached properties

Socket.io also provides common connections, disconnects, and message events 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 for 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 the following:

The

code is as follows:


//requires HTTP modules to start the server and Socket.io


var http= require (' http '), io= require (' Socket.io ');


//Start server on port 8080


var server= http.createserver (function (req, res) {


//Send HTML headers and message


res.writehead (200,{' content-type ': ' text/html '});


res.end (' <h1>hello Socket lover!</h1> ');


});


Server.listen (8080);


//Create a Socket.io instance and pass it to the server


var socket= io.listen (server);


//Add a connection listener


socket.on (' Connection ', function (client) {


//Success! Now start listening for incoming messages


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 both the client and the server can push the message back and forth! Within the Nodejs script, you can use simple JavaScript to create a recurring message transmitter:

The

code is as follows:


//Create a transmitter that sends messages to the client periodically (every 5 seconds)


var interval= setinterval (function () {


Client.send (' This is a "message from the server! ' + new Date (). GetTime ());


},5000);

The server side will push messages 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, and is used for long-polling substitution 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:

The

code is as follows:


var args, ws= typeof websocket!= ' undefined ';


var socket= 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 "instead of a raw body


dojo.xhrpost (args);


};


});


var sessionId;


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 automatic reconnection when a socket loses its connection. Expect to include Dojox. The Dojo 1.6 version of the socket is released early.

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.

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.