nuxt vue websocket接入

import { Component,Vue } from "vue-property-decorator";
import Axios from 'axios'
// 当前长链接的实例
export let wsInstance: WebSocket | null = null
export type StateType = 'connecting' | 'connected' | 'closing' | 'closed'   

// 检查长链接状态
export function checkWebSocketState(instan:WebSocket):StateType {
  if(!instan)return 'closed'
  let state:StateType="closed"
  switch(instan.readyState) {
    case WebSocket.CONNECTING:
      state="connecting"
      break;
    case WebSocket.OPEN:
      state="connected"
      break;    

    case WebSocket.CLOSING:
      state="closing"
      break;
    case WebSocket.CLOSED:
      state="closed"
      break;
    default:
      state="closed"
      break;
  }
  return state
}
@Component({
	name: 'myWebsocket',
})
export default class MyWebsocket extends Vue {


/** ws 状态 */
stateType:StateType = 'closed'

ws: WebSocket | null = null

token:string=""


changeState(type: StateType) {
  this.stateType = type
}

/** 发送保活信息的 setInterval id */
keepAliveId = 0

/** 连接 ws */
async connect() {
  let requestUrl=""

  return new Promise<void>((resolve, reject) => {
    if(this.ws || wsInstance)this.setInitState()
    
    if (this.stateType !== 'closed') throw Error('WS is used!')
    const wsPath=requestUrl+"/myws"
    this.ws = new WebSocket((location.protocol.split(":")[0]==="http" ? 'ws' : 'wss')+'://'+wsPath)
    wsInstance=this.ws

    this.changeState('connecting')
    let _this = this;
    this.ws.onopen = function (event) {
      _this.changeState('connected')
      // 发送保活信息
      // _this.keepAliveId = window.setInterval(() => {
      //   if (_this.ws && _this.ws.readyState === _this.ws.OPEN) {
      //     _this.ws.send('0')
      //   } else {
      //     window.clearInterval(_this.keepAliveId)
      //   }
      // }, 20 * 1000)
      resolve()
    }
    this.ws.onmessage = function(event) {
      let eventData = event.data
      try {
        eventData = JSON.parse(eventData)
      } catch {}
    }      
    this.ws.onclose = function(event) {
      // 如果当前还处于连接中,说明初始化ws连接失败
      if (_this.stateType === 'connecting') {
        reject(Error('ws connect failed!'))
      }
      _this.ws = null
      wsInstance=null
      _this.changeState('closed')
      
    }
  })
}

sendMessage(params:any){

  return new Promise((resolve:Function,reject:Function)=>{
    if (this.ws && this.ws.readyState === this.ws.OPEN) {
      this.ws.send(JSON.stringify(params))
      resolve()
    } else{
      reject("ws connect failed!")
    }
  })
}
/** 断开连接 */
disconnect() {
  const instan= this.ws || wsInstance
  if(instan!==null){
    this.ws?.close()
    wsInstance?.close()
  }
}
setInitState(){
  const instan= this.ws || wsInstance
  if(instan){
    let state:StateType=checkWebSocketState(instan)
    if(['closing','closed'].includes(state)){
      state="closed"
    }
    this.changeState(state)
    console.log("ws 状态"+this.stateType)
  }
}
}
Vue.js中直接操作TCP协议接口通常不是最佳实践,因为JavaScript作为客户端语言,它的安全性限制不允许直接访问本地网络资源,包括TCP连接。然而,如果你的应用运行在一个支持Node.js的环境中,比如使用了Vite或Nuxt.js等底层基于Node的服务端渲染框架,那么你可以通过创建一个Node.js中间件来处理TCP通信。 以下是简单的步骤: 1. **创建Node.js服务器**:在项目根目录下创建一个名为`server.js`的文件,使用`fastify`或`axios`等模块来建立一个HTTP服务器,这个服务器将充当TCP和Vue应用之间的桥梁。 ```javascript const fastify = require('fastify')(); const axios = require('axios'); fastify.post('/tcp', async (req, res) => { const tcpOptions = req.body; // 获取从Vue发送过来的TCP选项 try { const response = await axios.post('localhost:5000/tcp', tcpOptions); // 调用Node.js服务器的另一个端口 res.send(response.data); } catch (err) { res.status(500).send(err.message); } }); fastify.listen(3000, (err) => { if (err) throw err; console.log('Server listening on http://localhost:3000'); }); ``` 2. **Vue组件调用**:在Vue组件里,你可以使用axios发起POST请求到`http://localhost:3000/tcp`,传递你要发送给TCP服务器的数据。 ```vue <template> <!-- ... --> </template> <script> import axios from 'axios'; export default { methods: { sendDataToTcp(options) { axios.post('/tcp', options) .then(response => { // 处理响应 }) .catch(error => { // 处理错误 }); }, }, }; </script> ``` 注意这仅适用于特定情况,如允许的代理设置或特殊的安全策略。在生产环境,更推荐使用WebSocket或消息队列来进行长连接通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值