node与vue2 websocket

websocket.vue

<template>
  <div>websocket</div>
</template>

<script>
import { createSocket, sendWSPush, sendPing } from "@/utils/websocket";
export default {
  data() {
    return {
      //声明一个变量来注册监听事件
      getSocketData: null,
      // url: "ws://82.157.123.54:9010/ajaxchattest",
      url: "ws://127.0.0.1:8100",
    };
  },
  mounted() {
    this.init();
    //添加监听器
    // window.addEventListener("resize", this.setNavLeft);
  },
  destroyed() {
    console.log(111111111111);
    //移除监听器
    // document.removeEventListener("scroll", this.handleScroll, true);
    // window.removeEventListener("resize", this.setNavLeft);
    window.removeEventListener("onmessageWS", this.getSocketData);
  },
  methods: {
    // listenerFunction(e) {
    //   document.addEventListener("scroll", this.handleScroll, true);
    // },
    init() {
      //页面初始化的时候开启WebSocket
      createSocket(this.url);
      // 创建接收消息函数
      this.getSocketData = (e) => {
        console.log("e: ", e);
        const data = JSON.parse(e && e.detail.data);
        console.log("data: ", data);
        //这边编写处理服务端消息代码
      };
      //注册监听事件
      window.addEventListener("onmessageWS", this.getSocketData);
    },
  },
};
</script>

<style lang="scss" scoped></style>

websocket.js

import { Message } from "element-ui";

let Socket = "";
let ping = "ping";
let timeout = 5000; //心跳间隔时间
let setIntervalWesocketPush = null; // 执行心跳的定时器
let serverTimeoutObj = null; // 服务器超时定时器
// Socket.readyState 表示连接状态
// 0 表示连接尚未建立
// 1 表示连接已建立,可以进行通信
// 2 表示连接正在进行关闭
// 3 表示连接已关闭或者连接不能打开
//缓存ip
let ip = "";
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = (url) => {
  console.log(333333333333);
  Socket && Socket.close();
  if (!Socket) {
    console.log("正在建立websocket连接");
    //建立连接的时候缓存服务端ip以便于其他方法调用
    ip = url;
    Socket = new WebSocket(url);
    //发送心跳
    Socket.onopen = onopenWS;
    //接收消息
    Socket.onmessage = onmessageWS;
    //连接失败重连
    Socket.onerror = onerrorWS;
    //断开重连
    Socket.onclose = oncloseWS;
  } else {
    console.log("websocket已连接");
  }
};

/**打开WS之后发送心跳 */
const onopenWS = () => {
  sendPing();
  if (Socket.readyState == 0) {
    Message.warning("websocket 未连接");
  } else if (Socket.readyState == 1) {
    Message.success("websocket 连接成功");
  }
};

/**WS数据接收统一处理 */
const onmessageWS = (e) => {
  console.log("接收到数据", e);
  window.dispatchEvent(
    new CustomEvent("onmessageWS", {
      detail: {
        data: e.data,
      },
    })
  );
};

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = (message) => {
  setTimeout(() => {
    if (Socket.readyState === 0) {
      connecting(message);
    } else {
      Socket.send(JSON.stringify(message));
    }
  }, 1000);
};

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = (message) => {
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close();
    createSocket(ip);
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(message));
  } else if (Socket.readyState === 0) {
    connecting(message);
  }
};

/**断开重连 */
const oncloseWS = () => {
  clearInterval(setIntervalWesocketPush);
  console.log("websocket已断开....正在尝试重连");
  console.log("Socket1: ", Socket);
  if (Socket.readyState !== 2) {
    Socket = null;
    createSocket(ip);
  }
};

/**连接失败重连 */
const onerrorWS = () => {
  Socket.close();
  clearInterval(setIntervalWesocketPush);
  console.log("连接失败重连中");
  console.log("Socket2: ", Socket);
  if (Socket.readyState !== 3) {
    Socket = null;
    createSocket(ip);
  }
};

/**发送心跳
 * @param {number} timeout 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = () => {
  console.log(111111111);
  clearInterval(setIntervalWesocketPush);
  Socket.send(ping);
  setIntervalWesocketPush = setInterval(() => {
    console.log(2222222222);
    Socket.send(ping);
  }, timeout);
};

node服务端

server.js

const WebSocket = require('ws')
const PORT = 8100
const server = new WebSocket.Server({port: PORT})
server.on('open', function open() {
  console.log('connected')
})

server.on('close', function close() {
  console.log('disconnected')
})
// 监听连接事件
server.on('connection', function connection(ws, req) {
  const ip = req.socket.remoteAddress
  const port = req.socket.remotePort
  const clientName = ip + port

  // 发送数据
  ws.send(JSON.stringify("Welcome"))
  const form = {
    id: 1,
    nickname: "ru",
    email: "123456@qq.com",
    content: "I love programming"
  };

  // setInterval(() => {
  //   ws.send(JSON.stringify(message))
  // }, 3000)
  // ws.send(JSON.stringify(form))
  // 监听消息事件
  ws.on('message', function incoming(message) {
    console.log('received: %s', message)
    if (message === "ping") {
      ws.send("pong");
      console.log(111111)

    } else {
      console.log(2222222)
    }
    server.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {   //  等于1  正常通信
        // client.send(JSON.stringify(form))
        // client.send(JSON.stringify("Welcome22"))
        // ws.send(JSON.stringify("Welcome11"))
      }
    })
  })
})

server.on('listening', () => {
  console.log("连接成功");
  console.log('WebSocket服务器已启动并在运行');
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值