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>
相关推荐
涟漪海洋1 小时前
基于Netty的UDPServer端和Client端解决正向隔离网闸数据透传问题
网络
小疆智控3 小时前
从离散控制到集成管理:Modbus TCP转CANopen网关重构烟丝膨胀生产线
网络协议·tcp/ip·重构
国际云,接待3 小时前
微软云注册被阻止怎么解决?
服务器·网络·microsoft·云原生·微软·云计算
laocooon5238578863 小时前
基于Python的TCP应用案例,包含**服务器端**和**客户端**的完整代码
网络·python·tcp/ip
Blossom.1185 小时前
基于区块链的去中心化身份验证系统:原理、实现与应用
运维·服务器·网络·人工智能·机器学习·去中心化·区块链
沐森5 小时前
基于Fetch的post sse实现
网络协议
SZ1701102316 小时前
HTTP 请求报文 方法
网络·网络协议·http
Bruce_Liuxiaowei6 小时前
使用Nmap探测VNC服务信息—某单位KVM设备
网络·安全·web安全
比奥利奥还傲.6 小时前
QNAP威联通NAS配置SFTP与内网穿透技术实现远程文件访问
网络
君鼎7 小时前
C++操作系统与网络编程(针对特定岗位)
网络·c++