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>
相关推荐
Think Spatial 空间思维13 分钟前
【HTTPS基础概念与原理】TLS握手过程详解
数据库·网络协议·https
2501_915909061 小时前
开发日常中的抓包工具经验谈:Charles 抓包工具与其它选项对比
websocket·网络协议·tcp/ip·http·网络安全·https·udp
Johny_Zhao1 小时前
Vmware workstation安装部署微软SCCM服务系统
网络·人工智能·python·sql·网络安全·信息安全·微软·云计算·shell·系统运维·sccm
会员果汁1 小时前
网络实验-VRRP
网络
XiaoCCCcCCccCcccC1 小时前
Linux 的 UDP 网络编程 -- 回显服务器,翻译服务器
linux·网络·udp
獨枭2 小时前
Visual Studio 2022 跨网络远程调试
网络·ide·visual studio
深度学习04072 小时前
【网络实验】-BGP-EBGP的基本配置
网络·智能路由器
阿斯顿法国红酒快2 小时前
Windows系统安全加固
网络·windows·安全·网络安全·系统安全·ddos
sun0077003 小时前
windows 10 做服务器 其他电脑无法访问,怎么回事?
运维·服务器·网络
2401_896008194 小时前
TCP连接状态说明
运维·服务器·网络