Home  >  Article  >  Web Front-end  >  New protocol in HTML5: Example of WebSocket protocol

New protocol in HTML5: Example of WebSocket protocol

不言
不言Original
2018-08-08 10:02:291821browse

This article brings you an example of a new protocol in HTML5: WebSocket protocol. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

WebSocket is a new protocol in HTML 5. It performs full-duplex communication based on TCP connection.

Full-duplex communication: Indicates that data is allowed to be transmitted in both directions simultaneously. .

Determine whether the browser supports WebSocket

// 判断浏览器是否支持 WebSocket
if (window.WebSocket != undefined)
 {    
    var Socket = new WebSocket('ws://localhost: 8080')
  }

ws protocol is a new protocol for WebSocket. In addition, there is wss protocol, which represents the encrypted WebSocket protocol. The relationship between the two is like the HTTP protocol corresponding to the HTTPS protocol.

WebSocket Example

// 创建 WebSocket 实例
var Socket = new WebSocket('ws://localhost:8080')
// 连接打开
Socket.addEventListener('open', function(event) {
    socket.send('Hello Server!')
})
// 建通数据传送,有数据到达时触发
Socket.addEventListener('message', function(event) {
    console.log('Message from Server', event.data)
})
// 当错误发生时,用于监听 error 事件的事件监听器
Socker.addEventListener('error', function(event) {
    console.log(event.data)
})
// 连接关闭
Socket.addEventListener('close', function(event){
    console.log(event.data)
})

Recommended related articles:

HTML5 Application: Offline Application and Storage Application

HTML tag: summary of usage of img tag

The above is the detailed content of New protocol in HTML5: Example of WebSocket protocol. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn