标签:examples api develop stat content pre err pen master
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Websocket demo</title> </head> <body> <dl> <dt>参考文档</dt> <dd><a href="http://www.ruanyifeng.com/blog/2017/05/websocket.html" target="_blank">WebSocket 教程 - 阮一峰</a></dd> <dd><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket" target="_blank">WebSocket参考文档</a></dd> <dd><a href="https://github.com/joewalnes/websocketd" target="_blank">WebSocket 服务器 - websocketd(后台脚本不限语言)</a></dd> <dd><a href="https://github.com/joewalnes/websocketd/tree/master/examples" target="_blank">WebSocket 服务器 - websocketd(examples)</a></dd> <dd><a href="https://github.com/joewalnes/web-vmstats" target="_blank">WebSocket 浏览器实时展示服务器状态的案例(for Linux)</a></dd> </dl> <script> // 1.创建 WebSocket 对象 var socket = new WebSocket("wss://echo.websocket.org"); console.log(socket.readyState) //0 - 连接尚未建立 //2.连接打开时触发 socket.onopen = function (event) { console.log(socket.readyState) //1 - 连接已建立,可以进行通信 // 向服务器发送数据的方法(将要发送的数据放入队列) socket.send("Hello WebSockets!"); console.log(‘队列中等待传输的 UTF-8 文本字节数‘, socket.bufferedAmount) //队列中等待传输的 UTF-8 文本字节数。 }; //3.客户端接收服务端数据时触发 socket.onmessage = function (event) { // 接收服务器返回的数据 console.log("Received Message: " + event.data); // 关闭连接的方法 socket.close(); console.log(socket.readyState) //2 - 连接正在关闭 }; //4.通信发生错误时触发 socket.onerror = function (event) { console.log(socket.readyState) //3 - 连接已经关闭 }; //5.连接关闭时触发 socket.onclose = function (event) { console.log(socket.readyState) //3 - 连接已经关闭 }; </script> </body> </html>
标签:examples api develop stat content pre err pen master
原文地址:https://www.cnblogs.com/heroljy/p/9963193.html