websocket学习
<template> <!-- {{flag}} --> <div id="myChart" :style="{ width: '300px', height: '300px' }"></div> </template> <script setup> // 导入echarts import * as echarts from 'echarts' // 配置项 const option = reactive({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: [150, 230, 224, 218, 135, 147, 260], type: 'line' }] }); const initeCharts = () => { let myChart = echarts.init(document.getElementById('myChart')) // 绘制图表 myChart.setOption(option) } // 生命周期函数 onMounted(() => { initeCharts() }) // websocket 实现数据的实时更新 // 1. 新建对象 const ws = new WebSocket("ws://127.0.0.1:3000") // console.log(ws) // 2. 开始连接 ws.onopen = function() { alert('WebSocket连接成功') } ws.onerrow = function() { alert('WebSocket连接失败') } // 获取到的数据 这里会不断的接收后端返回的数据 ws.onmessage = function(data) { alert(data) } </script> <style scoped> .logo { height: 6em; padding: 1.5em; will-change: filter; transition: filter 300ms; } .logo:hover { filter: drop-shadow(0 0 2em #646cffaa); } .logo.vue:hover { filter: drop-shadow(0 0 2em #42b883aa); } </style>
后端 nodejs
var ws = require("nodejs-websocket") var PORT = 3000 var server = ws.createServer(function(conn) { console.log("New connection") conn.on("text", function(str) { console.log("Received " + str) conn.sendText(str.toUpperCase() + "!!!") }) conn.on("close", function(code, reason) { console.log("Connection closed") }) conn.on("error", function(err) { console.log("handle err"); console.log(err); console.log(err); }) }).listen(PORT)