Home > Article > Web Front-end > New protocol in HTML5: Example of WebSocket protocol
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!