Let's take you to know WebSocket in HTML5 and html5websocket.
This article mainly introduces WebSocket in HTML5. This article explains what WebSocket API in HTML5 is, how to use WebSocket API in HTML5, and how to use WebSocket with Socket. IO WebSocket, NodeJS, and Socket. i/O joint development and other content. For more information, see
Understand HTML5 WebSocket
In HTML5 specifications, my favorite Web technology is the rapidly becoming popular WebSocket API. WebSocket provides a popular technology to replace the Ajax technology we have been using over the past few years. This new API provides a method to effectively push messages from the client to the server using simple syntax. Let's take a look at HTML5 WebSocket API: it can be used on clients and servers. In addition, there is an excellent third-party API called Socket. IO.
1. What is the WebSocket API in HTML5?
WebSocket API is the asynchronous communication method of the Next Generation client-server. This communication replaces a single TCP socket. It uses ws or wss protocol and can be used for any client or server program. WebSocket is currently standardized by W3C. WebSocket has been supported by browsers such as Firefox 4, Chrome 4, Opera 10.70, and Safari 5.
The greatest advantage of WebSocket APIS is that servers and clients can push information to each other at any time within a given time range. WebSocket is not limited to Ajax (or XHR) communication. Because Ajax requires the client to initiate a request, the WebSocket server and client can push information to each other. XHR is restricted by the domain, webSocket allows cross-origin communication.
Ajax is clever, but it is not designed to be used. WebSocket is created for the specified destination and used to push messages in two directions.
Ii. WebSocket API usage in HTML5
Only focus on the client API, because each server language has its own API. The following code snippet is used to open a connection, create an event listener for the connection, disconnect the connection, send the message to the server, and close the connection.
The Code is as follows:
// Create a Socket instance
Var socket = new WebSocket ('ws: // localhost: 100 ');
// Open the Socket
Socket. onopen = function (event ){
// Send an initialization message
Socket. send ('I am the client and I \' m listening! ');
// Listen for messages
Socket. onmessage = function (event ){
Console. log ('client received ed a message', event );
};
// Disable the listening 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 above initialization snippet. The parameter is URL, and ws indicates WebSocket protocol. The onopen, onclose, and onmessage Methods connect the event to the Socket instance. Each method provides an event to indicate the status of the Socket.
The onmessage event provides a data attribute that can contain the Body of the message. The Body of a message must be a string that can be serialized or deserialized to transfer more data.
WebSocket syntax is very simple. It is incredibly easy to use WebSockets ...... Unless the client does not support WebSocket. Internet Explorer currently does not support WebSocket communication. If your client does not support WebSocket communication, you can use the following backup solutions:
Flash technology-Flash can provide a simple replacement. Flash is not installed on all clients, and some clients, such as iPhone/iPad, do not support Flash.
AJAX Long-Polling technology-it has been some time in the industry to use AJAX long-polling to simulate WebSocket. It is a feasible technique, but it cannot optimize the sent information. That is to say, it is a solution, but it is not the best technical solution.
Currently, browsers such as IE do not support WebSocket. What should we do if we want to provide WebSocket event processing, return transmission, and use a unified API on the server? Fortunately, Guillermo Rauch creates a Socket. IO technology.
3. WebSocket with Socket. IO
Socket. IO is a WebSocket API created by Guillermo Rauch. Guillermo Rauch is the chief technology officer of LearnBoost and Chief Scientist of LearnBoost labs. Socket. IO uses the detection function to determine whether to establish a WebSocket connection, AJAX long-polling connection, or Flash. Allows you to quickly create real-time applications. Socket. IO also provides a NodeJS API, which looks very similar to the client API.
Create client Socket. IO
Socket. IO can be downloaded from GitHub. You can include the socket. io. js file to 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. It is time to create the Socket:
The Code is as follows:
// Create a Socket. IO instance and establish a 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 to close the connection
Socket. on ('disconnect', function (){
Console. log ('the client has disconnected! ');
});
// Send a message to the server through Socket
Function sendMessageToServer (message ){
Socket. send (message );
}
Socket. IO simplifies WebSocket APIs and unifies the APIS returned for shipping. Transmission includes:
WebSocket
Flash Socket
AJAX long-polling
AJAX multipart streaming
IFrame
JSONP polling
You can also set the second option of any Socket. IO constructor. The options include:
Port-the port to be connected
Transports-an array containing different transmission types
TransportOptions-objects used for transmitted parameters, with additional attributes
Socket. IO also provides common connections, disconnection, and message events provided by the local WebSocket API. Socket also provides methods to encapsulate each event type.
Iv. Joint development of NodeJS and Socket. IO
The server-side solution provided by Socket. IO allows unified client-side and server-side APIs. With Node, you can create a typical HTTP server and then pass the server instance to Socket. IO. Here, you create a connection, disconnect a connection, and create a message listener, just like the client.
A simple server script looks like this:
The Code is as follows:
// The HTTP module is required 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! Listen to received 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. If NodeJS is installed, run the following command from the command line:
Node socket-server.js
Now both the client and server can push messages back and forth! In the NodeJS script, you can use simple JavaScript to create a regular message sender:
The Code is as follows:
// Create a sender that regularly sends messages to the client every 5 seconds.
Var interval = setInterval (function (){
Client. send ('this is a message from the server! '+ New Date (). getTime ());
},5000 );
The server pushes messages to the client every five seconds.
V. dojox. Socket and Socket. IO
Persevere creator Kris Zyp creates dojox. Socket. Dojox. Socket encapsulates the WebSocket API in the same way as the Dojo library. It is used to replace long-polling when the client does not support WebSocket.
The following example shows how to use dojox. Socket on the client and Socket. IO on the server:
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 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 automatic reconnection when the socket loses connection. We look forward to the early release of the Dojo 1.6 version containing dojox. Socket.
Vi. Practical Application and WebSocket Resources
There are many practical applications of WebSocke. WebSocket is ideal for most client-server asynchronous communication, and chat in a browser is the most prominent application. Because of its high efficiency, WebSocket is used by most companies.
HTML5 WebSocket resources are organized as follows:
Socket. IO site: http://socket.io/
Wikipedia: http://en.wikipedia.org/wiki/WebSockets of WebSocket
WebSockets.org site: http://www.websockets.org/
Dojo WebSocket site: http://www.sitepen.com/blog/2010/10/31/dojo-websocket/