This article mainly introduces you to know HTML5 in the WebSocket, this article explains HTML5 in the WebSocket API is what east, HTML5 in the
WebSocket API usage, with Socket.io WebSocket, Nodejs and Socket.io joint development and other content, the need for friends can refer to the following
Meet HTML5 's WebSocket
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.
One, HTML5 in the WebSocket API is a what stuff?
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.
Ii. usage of the WebSocket API in HTML5
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.
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 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 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:
1 <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:
//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);
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 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.
HTML5 WebSocket related resources are organized as follows:
Socket.io site: Http://socket.io/WebSocket wikipedia:http://en.wikipedia.org/wiki/websockets websockets.org site: http ://www.websockets.org/dojo websocket site: http://www.sitepen.com/blog/2010/10/31/dojo-websocket/
Take you to know the WebSocket in HTML5