Meet HTML5 's WebSocket

Source: Internet
Author: User
Tags learnboost

Knowing HTML5 's websocket 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 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.

[Copy to Clipboard] [- ]code://Creating 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 messages
Socket.onmessage = function (event) {
Console.log (' Client received a message ', event);
};

Monitor the closing of the socket
Socket.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.

WebSocket's syntax 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:

Flash TechnologyThe--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 technology, but it does not optimize the information sent. In other words, it is a solution, but not the best technical solution.

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

three, with Socket.io of WebSocket

Socket.io is Guillermo Rauch created WebSocket Api,guillermo Rauch is chief technology officer of Learnboost Company and chief scientist of Learnboost Lab. 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 the Socket.io.js file can be included in the page:

[Copy to Clipboard] [- ]Code:<script src= "Http://cdn.socket.io/stable/socket.io.js" ></script>
[/code

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

[Code]
Create a Socket.io instance to establish a connection
var socket= new IO. Socket (' localhost ', {
port:8080
});
Socket.connect ();

Add a connection Listener
Socket.on (' Connect ', function () {
Console.log (' Client have 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 to close the connection
Socket.on (' Disconnect ', function () {
Console.log (' The client has disconnected! ');
});

Send a message to the server via the socket
function sendmessagetoserver (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:

[Copy to Clipboard] [- ]code://requires an HTTP module to start the server and Socket.io
var http= require (' http '), io= require (' Socket.io ');

Start the 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 (' });
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! 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:

[Copy to Clipboard] [- ]Code: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:

[Copy to Clipboard] [- ]CODE://Create a regular (every 5 seconds) send message to the client's transmitter
var interval= setinterval (function () {
Client.send (' This was a message from the server! ' + 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:

[Copy to Clipboard] [- ]Code: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 the message 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 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.

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.