In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 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 "html5's websockets full-duplex communication example analysis". 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!
At present, the implementation of real-time Web applications is mostly focused on polling and other server-side push technologies, the most famous of which is Comet. Comet technology allows the server to actively push data to the client asynchronously.
When polling is used, the browser sends a HTTP request periodically and then receives a response; when long polling is used, the browser sends a request to the server and the server keeps it open for a period of time; when using the streaming solution, the browser sends a full HTTP request, but the server sends and maintains an open response that is continuously updated and open indefinitely.
The above three methods all involve HTTP request and response packet headers when sending real-time data, and contain a lot of extra and unnecessary header data, which will cause transmission delay.
I. interpretation of HTML5 WebSockets
1. WebSocket handshake
In order to establish WebSocket communication, the client and server upgrade the HTTP protocol to WebSocket protocol during the initial handshake. Once the connection is established, WebSocket messages can be sent back and forth between the client and the server in full-duplex mode.
Note: in the network, each message begins with 0x00 bytes and ends with 0xFF, and the intermediate data is encoded in UTF-8 format.
2. WebSocket interface
In addition to the definition of the WebSocket protocol, the WebSocket interface for JavaScript applications is also defined.
Copy the code
The code is as follows:
Interface WebSocket {
Readonly attribute DOMString URL
/ / ready state
Const unsigned short CONNECTING = 0
Const unsigned short OPEN = 1
Const unsigned short CLOSED = 2
Readonly attribute unsigned short readyState
Readonly attribute unsigned short bufferedAmount
/ / Network
Attribute Function onopen
Attribute Function onmessage
Attribute Function onclose
Boolean send (in DOMSString data)
Void close ()
}
WebSocket implements EventTarget
Note: the ws:// and wss:// prefixes denote WebSocket connections and secure WebSocket connections, respectively.
II. HTML5 WebSockets API
This section discusses how to use HTML5 WebSockets
1. Check whether the browser supports it.
Use window.WebSocket to determine whether the browser supports it or not.
2. The basic usage of API
A. creation of WebSocket object and connection to WebSocket server
Copy the code
The code is as follows:
Url = "ws://localhost:8080/echo"
Ws = new WebSocket (url)
b. Add event listener
WebSocket follows the asynchronous programming model. After opening socket, you only need to wait for the event to occur instead of actively polling the server, so you need to add a callback function to listen for the event.
The WebSocket object has three events: open, close, and message. The open event is triggered when the connection is established, the message event is triggered when a message is received, and the close event is triggered when the WebSocket connection is closed.
Copy the code
The code is as follows:
Ws.onopen = function () {
Log ("open")
}
Ws.onmessage = function () {
Log (e.data)
}
Ws.onclose = function () {
Log ("closed")
}
c. Send a message
When socket is open (that is, after the onopen listener is called and before the onclose listener is called), you can use the send method to send a message.
Ws.send ("Hello World")
Third, HTML5 WebSockets application example
This section combines the Geolocation interface described earlier to create an application that calculates the distance directly in the Web page.
1. Write HTML files
Copy the code
The code is as follows:
HTML5 WebSocket / Geolocation tracker
HTML5 WebSocket / Geolocation tracker
Geolocation: your browser does not support HTML5 Geolocation
WebSocket: your browser does not support HTML5 Web Sockets
/ / reference to WebSocket
Var ws
/ / the only random ID generated for the session
Var myId = Math.floor (100000*Math.random ())
/ / number of rows currently displayed
Var rowCount
Function updateSocketStatus (message) {
Document.getElementById ("socketStatus") [xss_clean] = message
}
Function updateGeolocationStatus (message) {
Document.getElementById ("geoStatus") [xss_clean] = message
}
Function loadDemo () {
/ / make sure the browser supports WebSocket
If (window.WebSocket) {
Url = "ws://localhost:8080"; / / broadcast WebSocket server location
Ws = new WebSocket (url)
Ws.onopen = function () {
UpdateSocketStatus ("connection established")
}
Ws.onmessage = function (e) {
UpdateSocketStatus ("Update location data:" + dataReturned (e.data))
}
}
Var geo
If (navigator.geolocation) {
Geo = navigator.geolocation
UpdateGeolocationStatus ("browser supports HTML5 Geolocation")
}
Geo.watchPosition (updateLocation,handleLocationError, {maximumAge:20000}); / / updated every 20s
Function updateLocation (position) {
Var latitude = position.coords.latitude
Var longitude = position.coords.longitude
Var timestamp = position.timestamp
UpdateGeolocationStatus ("location update time:" + timestamp)
Var toSend = JSON.stringify ([myId,latitude,longitude])
SendMyLocation (toSend)
}
Function sendMyLocation (newLocation) {
If (ws) {
Ws.send (newLocation)
}
}
Function dataReturned (locationData) {
Var allData = JSON.parse (locationData)
Var incomingId = allData [1]
Var incomingLat = allData [2]
Var incomingLong = allData [3]
Var incomingRow = document.getElementById (incomingId)
If (! incomingRow) {
IncomingRow = document.getElementById ("div")
IncomingRow.setAttribute ("id", incomingId)
IncomingRow.userText = (incomingId = = myId)? "Me": 'User' + rowCount
RowCount++
Document.body.appendChild (incomingRow)
}
IncomingRowan [XSS _ clean] = incomingRow.userText + "/ / Lat:" +
IncomingLat + "/ / Lon:" +
IncomingLong
Return incomingRow.userText
}
Function handleLocationError (error) {
Switch (error.code) {
Case 0:
UpdateGeolocationStatus ("error retrieving location information:" + error.message)
Break
Case 1:
UpdateGeolocationStatus ("users prevent access to location information.")
Break
Case 2:
UpdateGeolocationStatus ("browser cannot detect your location information:" + error.message)
Break
Case 3:
UpdateGeolocationStatus ("browser timed out to retrieve location information.")
Break
}
}
This is the end of "html5's websockets full-duplex communication example analysis". 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.