Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use WebSocket API in HTML5

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to use WebSocket API in HTML5". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is the WebSocket API in HTML5?

WebSocket API is the next generation client-server asynchronous communication method. This communication replaces a single TCP socket, uses ws or wss protocols, and can be used for any client and server program. WebSocket is currently standardized by the W3C. WebSocket is already supported by browsers such as Firefox 4, Chrome 4, Opera 10.70, and Safari 5.

The greatest thing about WebSocket API is that the server and client can push information to each other at any time within a given time frame. WebSocket is not limited to Ajax (or XHR) communication, because Ajax technology requires clients to initiate requests, and WebSocket servers and clients can push information to each other; XHR is limited by domains, while WebSocket allows cross-domain communication.

The clever thing about Ajax technology is that there is no way to design it to use. WebSocket is created for the specified destination and is used to push messages in both directions.

Second, the usage of WebSocket API in HTML5

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

Copy the code

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 Iram listeningmakers')

/ / listen for messages

Socket.onmessage = function (event) {

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

}

/ / listen to the shutdown of Socket

Socket.onclose = function (event) {

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

}

/ / close Socket....

/ / socket.close ()

}

Let's look at the initialization snippet above. The parameter URL,ws indicates the WebSocket protocol. The onopen, onclose, and onmessage methods connect events to the Socket instance. Each method provides an event to represent the state of the Socket.

The onmessage event provides a data property that can contain the Body portion 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 WebSocket is very simple, and using WebSockets is incredibly easy. Unless the client does not support WebSocket. IE browsers currently do not support WebSocket communication. If your client does not support WebSocket communication, here are some backup solutions 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's long-polling to simulate WebSocket has been in the industry for some time. It is a feasible technology, but it cannot optimize the information sent. In other words, it is a solution, but not the best technical solution.

Since current browsers such as IE do not support WebSocket, what should we do to provide WebSocket event handling, return transmission, and use a unified API on the server side? Fortunately, Guillermo Rauch created a Socket.IO technology.

3. WebSocket with Socket.IO

Socket.IO, founded by Guillermo Rauch, WebSocket API,Guillermo Rauch is the chief technology officer of LearnBoost and the chief scientist of LearnBoost Labs. Socket.IO uses the detection function to determine whether to establish a WebSocket connection, or an AJAX long-polling connection, or a Flash, and so on. You can quickly create real-time applications. Socket.IO also provides a NodeJS API that looks very much like a client-side API.

Establish client-side Socket.IO

Socket.IO can be downloaded from GitHub, and the socket.io.js file can be included in the page:

Copy the code

The code is as follows:

At this point, Socket.IO is valid on this page, and it's time to create a Socket:

Copy the code

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 serverware recording journal data)

});

/ / add a listener that closes the connection

Socket.on ('disconnect',function () {

Console.log ('The client has disconnect')

});

/ / send a message to the server via Socket

Function sendMessageToServer (message) {

Socket.send (message)

}

Socket.IO simplifies WebSocket API and unifies the API for return transport. Transmissions include:

WebSocket

Flash Socket

AJAX long-polling

AJAX multipart streaming

IFrame

JSONP polling

You can also set the second option for any Socket.IO constructor, including:

Port-Port to be connected

Transports-an array containing different transport types

TransportOptions-the object used by the transmitted parameter, with additional properties

Socket.IO also provides normal connections, disconnections, 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

Socket.IO provides a server-side solution that allows unified client-side and server-side API. With Node, you can create a typical HTTP server and pass an instance of the server to Socket.IO. From here, you create a connection, disconnect it, and set up a message listener, just as you do on the client.

A simple server-side script looks like this:

Copy the code

The code is as follows:

/ / A 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 headers and message of HTML

Res.writeHead (200,{ 'Content-Type':' text/html'})

Res.end ('Hello Socket override')

});

Server.listen (8080)

/ / create an instance of Socket.IO 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 received messages.

Client.on ('message',function (event) {

Console.log ('Received message from clientproof event)

});

Client.on ('disconnect',function () {

ClearInterval (interval)

Console.log ('Server has disconnected')

});

});

You can run the server section, assuming that NodeJS is installed, from the command line:

Node socket-server.js

Now both the client and the server can push messages back and forth! Within the NodeJS script, you can use a simple JavaScript to create a periodic message sender:

Copy the code

The code is as follows:

/ / create a sender that sends messages to the client on a regular basis (every 5 seconds)

Var interval= setInterval (function () {

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

}, 5000)

The server will push the message to the client every 5 seconds.

5. Dojox.Socket and Socket.IO

Kris Zyp, the creator of Persevere, created dojox.Socket. Dojox.Socket encapsulates WebSocket API in a consistent way with the Dojo library, which is used to use long-polling alternatives when the client does not support WebSocket.

Here are examples of how to use dojox.Socket on the client side and Socket.IO on the server side:

Copy the code

The code is as follows:

Var args, ws= typeof Web Sockets = '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) = ='~ hype') {

/ / a heartbeat

}

});

Dojox.socket.Reconnect also creates an automatic reconnection when the socket loses its connection. Look forward to the early release of Dojo 1.6, which includes dojox.Socket.

VI. Practical applications and WebSocket resources

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

This is the end of the content of "how to use WebSocket API in HTML5". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report