websocket客户端
<html> <head> <title>websocket客户端</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <div> <canvas id="myChart"></canvas> </div> <script> $(document).ready(function() { var arrayObj = new Array(); arrayObj.push(12); arrayObj.push(19); arrayObj.push(3); arrayObj.push(5); arrayObj.push(2); arrayObj.push(3); var ctx = document.getElementById('myChart'); var chart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: arrayObj, borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); // 创建websocket客户端 var socket = new WebSocket("ws://127.0.0.1:8765"); // 打开websocket socket.onopen = function(e) { socket.send("CMD"); }; // 接收服务器数据 socket.onmessage = function(event) { console.log(event.data); arrayObj[0] = arrayObj[1]; arrayObj[1] = arrayObj[2]; arrayObj[2] = arrayObj[3]; arrayObj[3] = arrayObj[4]; arrayObj[4] = arrayObj[5]; arrayObj[5] = event.data; chart.data.datasets[0].data = arrayObj; chart.update(); }; // 关闭websocket socket.onclose = function(event) { console.log('socket关闭'); }; // 错误处理 socket.onerror = function(error) { console.log(error.message); }; setInterval(function(){ socket.send("CMD"); },1000); }); </script> </body> </html>