vue3
<script setup> import { reactive, ref,onMounted ,onBeforeMount,onUnmounted} from 'vue' onMounted(() => { initWebsocket() }) onUnmounted(() => { WebSocketonclose() }) const ws = reactive({ socket: null, }) const initWebsocket = () => { const wsuri = "ws://10.54.19.175:7001/ws" ws.socket = new WebSocket(wsuri) ws.socket.onmessage = WebSocketonmessage ws.socket.onopen = WebSocketonopen ws.socket.onclose = WebSocketonclose ws.socket.onerror = WebSocketonerror } const WebSocketonopen = () => { const data={ test: '123' } WebSocketsend(JSON.stringify(data)) } const WebSocketonclose = (e) => { ws.socket && ws.socket.close() ws.socket = null } const WebSocketonmessage = (e) => { const data = JSON.parse(e.data) console.log(data) } const WebSocketonerror = (e) => { initWebsocket() } const WebSocketsend = (data) => { ws.socket.send(data) } </script>
node 后端 需要安装插件 [email protected]
config/plugin.js
module.exports = { // had enabled by egg // static: { // enable: true, // }io: { enable: true, package: 'egg-websocket-plugin', }, };
const { Controller } = require('egg'); class HomeController extends Controller { async index() { const { ctx } = this; ctx.body = 'hi, egg'; } async wsSocket() { const { ctx } = this; if (!ctx.websocket) { throw new Error('this function can only be use in websocket router'); } console.log('client connected'); const obj = { name: 'hello world' }; setInterval(() => { ctx.websocket.send(JSON.stringify(obj)); }, 2000); ctx.websocket .on('message', msg => { console.log('receive', msg); }) .on('close', (code, reason) => { console.log('websocket closed', code, reason); }); } } module.exports = HomeController;
标签:const,socket,简单,ctx,ws,使用,Websocket,websocket,data From: https://www.cnblogs.com/qq735675958/p/17994453