Vue3使用Websocket进行跨页面通信

安装

npm i ws

安装vue3响应式库

npm i @vue/reactivity

服务端创建连接--nodejs

javascript 复制代码
// Nodejs 端 index.js

// 引入 WebSocket 库
const WebSocket = require('ws');
// 引入 Vue 响应式 API
const reactivity = require('@vue/reactivity')

const {
    ref,
    computed,
    watch
} = reactivity

// 创建 WebSocket 服务器
const wss1 = new WebSocket.Server({
    port: 8001
});
const wss2 = new WebSocket.Server({
    port: 8002
});


// 记录数字
const count = ref(0)
// 计算出 10 倍
const sum = computed(() => 10 * count.value)

// 连接1
wss1.on('connection', (ws) => {
    // 处理来自客户端的消息
    ws.on('message', (message) => {
        // count 变化
        count.value = Number(String(message))
    });
    // 监听 count,并通知页面2
    watch(count, v => {
        ws.send(v)
    })
});

// 连接2
wss2.on('connection', (ws) => {
    // 处理来自客户端的消息
    ws.on('message', () => {
        // 执行清空命令
        count.value = 0
    });
    // 监听 sum,并通知页面2
    watch(sum, v => {
        ws.send(v)
    })

    // 模拟定时任务
    setTimeout(() => {
        ws.send(sum.value)
    }, 3600 * 12);
});

第一个页面连接8081--page1.vue

javascript 复制代码
<template>
  <div class="flex justify-center mb-3 text-4xl font-bold">页面1</div>
  <Button type="primary" @click="click">点击更新数据</Button>
  <div class="text-lg">当前数值:{{ count }}</div>
</template>

<script setup lang="ts">
import { Button } from 'ant-design-vue';
import { ref } from 'vue';

const count = ref(0);

// 创建 WebSocket 客户端
const socket = new WebSocket('ws://localhost:8001');

const click = () => {
  count.value++;
  // 发送消息到服务器
  socket.send(`${count.value}`);
};

// 接受服务端的消息
socket.addEventListener('message', e => {
  count.value = e.data;
});
</script>

第二个页面连接8082--page2.vue

javascript 复制代码
<template>
  <div class="flex justify-center mb-3 text-4xl font-bold">页面2</div>
  <Button type="primary" @click="click">清空数据</Button>
  <div class="text-lg">当前数值:{{ count }}</div>
</template>

<script setup lang="ts">
import { Button } from 'ant-design-vue';
import { ref } from 'vue';

const count = ref(0);

// 创建 WebSocket 客户端
const socket = new WebSocket('ws://localhost:8002');

const click = () => {
  // 发送消息到服务器
  socket.send('Hello, server!');
};

// 接受服务端的消息
socket.addEventListener('message', e => {
  count.value = e.data;
});
</script>
相关推荐
EasyNVR1 小时前
EasyRTC:开启智能硬件与全平台互动新时代
网络·音视频·webrtc·p2p·智能硬件·视频监控
红豆和绿豆6 小时前
如何发起http的请求,在系统中集成
网络·网络协议·http
Wlq04156 小时前
三种安全协议 IPSec & SSL & PGP
网络·安全·ssl
Liu-Eleven7 小时前
lwip和tcp/ip区别
网络·网络协议·tcp/ip
黑客Ash8 小时前
网络安全配置截图
网络·安全·web安全
x66ccff8 小时前
【nvidia】NCCL禁用P2P后果权衡
服务器·网络协议·p2p
xianwu54310 小时前
反向代理模块kd
开发语言·网络·数据库·c++·mysql
路由侠内网穿透10 小时前
无公网IP可实现外网访问群晖 WebDAV
网络·网络协议·tcp/ip·docker
垚垚 Securify 前沿站10 小时前
Apache Logic4j 库反序列化漏洞复现与深度剖析
linux·网络·安全·web安全·系统安全·apache
vvilkim11 小时前
TCP/IP协议
网络·网络协议·tcp/ip