首页 > 其他分享 >Vue WebSocket的实现 含断线重连

Vue WebSocket的实现 含断线重连

时间:2023-07-24 17:37:26浏览次数:40  
标签:Vue WebSocket void System private socketConn using new 重连

vue客户端 

main.js

import { createApp } from 'vue'
import { reactive } from 'vue'

import App from './App.vue'

import {webSocketUrl} from '/public/static/config.json'

let websock=null;

const app = createApp(App);

//读配置文件
app.config.globalProperties.$webSocketUrl=webSocketUrl;
console.log('读配置文件====',app.config.globalProperties.$webSocketUrl);

//初始化
async function init() {
  //连接websocket
  initWebSocket();
  //赋给全局对象
  app.config.globalProperties.$websock = websock;
   
}

websocket函数

//------------------------websocket------------------
function initWebSocket(){  

  //const wsuri = "ws://192.168.1.120:5011/chat/";
  const wsuri = app.config.globalProperties.$webSocketUrl;
  console.log("打开一个websocket " +wsuri); 

  websock = new WebSocket(wsuri);
  websock.onmessage =  websocketonmessage;
  websock.onopen =  websocketonopen;
  websock.onerror =  websocketonerror;
  websock.onclose =  websocketclose;
} 
function websocketonopen(){ //连接建立之后执行send方法发送数据
  //let actions = {"test":"12345"};
  //this.websocketsend(JSON.stringify(actions));
  let strMsg="@&l_login:1001,1001,1001";
  websocketsend(strMsg);
  console.log("连接建立成功 发 " +strMsg); 
} 
function websocketonerror(){
    console.log('连接建立失败');
    //initWebSocket();//连接失败不再重连,统一在断开连接函数处理
} 
function websocketonmessage(e){ //数据接收
  //const redata = JSON.parse(e.data);
  console.log("数据接收 " +e.data); 
  //收到消息处理函数 websocket_resMsg(e.data);
 
} 
function websocketsend(Data){//数据发送
  websock.send(Data);
} 
function websocketclose(e){  //关闭
  console.log('断开连接',e);
  //3秒后再次 请求连接webSocket
  setTimeout(reconnectWebSocket,3000);
} 
//重新连接webSocket
function reconnectWebSocket(){
    console.log("reconnectWebSocket重新连接======");
    initWebSocket();//重新连接
}
//-------------------------------------------------------
//执行初始化
app.use(init);

app.mount('#app');

在任意 子组件中 调用 websock对象 发消息

 this.$websock.send(msgData);

C# 编写的 websocket 服务器端

这篇C#端写的较为详细 https://www.cnblogs.com/hailexuexi/p/16854230.html

仅为示例,并不完善

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
 
using System.Collections;
using System.Security.Cryptography;

using System.Net;
using WebSocket;
using System.Threading;

namespace WebSockWinForm
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private int MaxBufferSize;
        private byte[] FirstByte;
        private byte[] LastByte;

        private int TcpPort = 5011;
        private Socket Listener;
            
        delegate void MyInvoke(string str);

        List<SocketConnection> connectionSocketList = new List<SocketConnection>();

        private System.Threading.Thread listenerThread;


        private void Form1_Load(object sender, System.EventArgs e)
        {
            m_StartDoListen();
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.m_StopDoListen();//关闭
        }

        //开始后台线程,开始侦听网络/端口
        private void m_StartDoListen()
        {
            MaxBufferSize = 1024 * 100;
            FirstByte = new byte[MaxBufferSize];
            LastByte = new byte[MaxBufferSize];

            listenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(m_DoListen));
            listenerThread.Start();
        }

        //开启后台侦听线程,
        private void m_DoListen()
        {
            this.StartServer();
        }

        private void m_StopDoListen()
        {
            if (Listener != null) Listener.Close();

            foreach (SocketConnection item in connectionSocketList)
            {
                item.ConnectionSocket.Close();
            }
            connectionSocketList.Clear();
            GC.SuppressFinalize(this);
        }

        public void StartServer()
        {
            try
            {
                Char char1 = Convert.ToChar(65533);

                Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                Listener.Bind(new IPEndPoint(this.m_GetIPV4Address(), TcpPort));

                Listener.Listen(500);//ConnectionsQueueLength

                this.m_ProcessMsg("StartListen..................");

                while (true)
                {
                    Socket sc = Listener.Accept();
                    
                    if (sc != null)
                    {
                        System.Threading.Thread.Sleep(5000);
                        SocketConnection socketConn = new SocketConnection();
                        socketConn.ConnectionSocket = sc;
                       
                        socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection);
                        socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage);
                        socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected);

                        socketConn.ConnectionSocket.BeginReceive(socketConn.receivedDataBuffer,
                                                                 0, socketConn.receivedDataBuffer.Length,
                                                                 0, new AsyncCallback(socketConn.ManageHandshake),
                                                                 socketConn.ConnectionSocket.Available);
                        connectionSocketList.Add(socketConn);
                    }
                }
            }
            catch (Exception ex)
            {
                //myClass.clsLogHelper.m_CreateErrorLogTxt("WebScript StartServer", "出错", ex.Message.ToString());
                Thread.CurrentThread.Abort();
            }
        }

        //有新的连接
        void socketConn_NewConnection(string name, EventArgs e)
        {
            this.m_ProcessMsg("有新的连接 " + name + " ");
        }
        //有断开连接
        void socketConn_Disconnected(Object sender, EventArgs e)
        {
            SocketConnection sConn = sender as SocketConnection;
            if (sConn != null)
            {
                this.m_ProcessMsg(sConn.Name + "已断开连接!");

                sConn.ConnectionSocket.Close();
                connectionSocketList.Remove(sConn);
            }
        }

        //广播
        void socketConn_BroadcastMessage(Object sender, string message, EventArgs e)
        {
            SocketConnection sConn = sender as SocketConnection;

            if (message.IndexOf("login:") != -1)
            {
                
                sConn.Name = message.Substring(message.IndexOf("login:") + "login:".Length); 
                this.m_ProcessMsg(" " + sConn.Name + "已连接到服务器!");

                message = string.Format("LoginOk!", message.Substring(message.IndexOf("login:") + "login:".Length)); 
            }
            this.m_ProcessMsg("收到: " + sConn.Name + " " + message);
            this.Send(message);   
        }

        public void Send(string message)
        {
            foreach (SocketConnection item in connectionSocketList)
            {
                if (!item.ConnectionSocket.Connected) return;
                try
                {
                    if (item.IsDataMasked)
                    {
                        DataFrame dr = new DataFrame(message);
                        item.ConnectionSocket.Send(dr.GetBytes());
                    }
                    else
                    {
                        item.ConnectionSocket.Send(FirstByte);
                        item.ConnectionSocket.Send(Encoding.UTF8.GetBytes(message));
                        item.ConnectionSocket.Send(LastByte);
                    }
                }
                catch (Exception ex)
                {
                    myClass.clsLogHelper.m_CreateErrorLogTxt("WebScript Send", "WebScript发送消息时出错", ex.Message.ToString());
                }
            }
        }


        #region 显示Tcp消息
        private void m_ProcessMsg(string statusMessage)
        {
            MyInvoke dh = new MyInvoke(m_DisplayMsg); //invokes为方法名
            this.Invoke(dh, new object[] { statusMessage });// step3 调用invoke
        }

        private void m_DisplayMsg(string str)
        {
            if (this.lstTcpMessage.Items.Count > 300)
            {
                this.lstTcpMessage.Items.Clear();//大于300条时清空
            }
            lstTcpMessage.Items.Add(str);//显示通信消息
        }
        #endregion


        #region 获取IP地址
        private  IPAddress m_GetIPV4Address()
        {
            string strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            foreach (IPAddress ip in ipEntry.AddressList)
            {
                //IPV4 手动固定IP地址
                if (ip.ToString() == "192.168.1.120")
                {
                    return ip;
                }
            }
            return ipEntry.AddressList[8];
        }
        #endregion

}
}

 

标签:Vue,WebSocket,void,System,private,socketConn,using,new,重连
From: https://www.cnblogs.com/hailexuexi/p/17577818.html

相关文章

  • VUEX笔记
    VUEX笔记statestate:{ ip:''}gettersconstgetters={ ip:state=>state.ip}mutations同步操作this.$store.commit()mutations:{ SET_IP:(state,ip)=>{ state.ip=ip }}actions异步操作this.$store.dispatch()Action类似于mutati......
  • 实现在Vue应用中播放实时视频,使用WebRTC技术和Canvas API来完成
    要实现在Vue应用中播放实时视频,您需要使用WebRTC技术和CanvasAPI来完成。下面是基本的实现步骤:1.使用getUserMediaAPI获取用户的摄像头和麦克风访问权限;javascript复制代码navigator.mediaDevices.getUserMedia({video:true,audio:true}).then(function(stream){//......
  • SpringBoot+Vue实现校园二手系统。前后端分离技术【完整功能介绍+实现详情+源码】
    前言       这个系统基本上可以改造为其它类似的系统。后台管理基本上一致。前台进行一些页面样式的改造就可以变成一个新的系统。有时间,做几个变体系统。       闲的无聊,把大学时候做的一个系统进行了重构。将项目拆分成完全前后端分离的形式。客户端采用一套、商家......
  • 前端系列16集-vue3范型,vue-i18n-next,watch,watchEffect
    中台落地手记——业务服务化与数据资产化vue-i18n-nextvue3中使用i18n需要安装的是 [vue-i18nv9] 的版本npminstallvue-i18n@9创建src\lang\index.ts,使用 createI18n 创建i18n实例://src\lang\index.tsimport{createI18n}from'vue-i18n'import{LANG_......
  • Vue项目启动 报错error:0308010C:digital envelope routines::unsupported
    出现这个错误是因为node.jsV17版本中最近发布的OpenSSL3.0,而OpenSSL3.0对允许算法和密钥大小增加了严格的限制,可能会对生态系统造成一些影响.解决方法package.json增加配置"scripts":{"serve":"setNODE_OPTIONS=--openssl-legacy-provider&&vue-cli-serviceserve......
  • Windows多重连接问题
    先叙述我的问题出现情况:我在Windows域账号中使用smb连接Linux服务器的共享文件夹时报多重连接的错,报错具体信息:“不允许一个用户使用一个以上用户名与服务器或共享资源的多重连接。中断与此服务器或共享资源的所有连接,然后再试一次。”查找并测试过但不成功的方法:1.删除Windows......
  • vue组件封装 - 选择器远程搜索下拉列表
    <!--*component:人员选择-远程搜索下拉列表*time:2023/7/19*author:zx*使用方式*importPersonSelectfrom"@/components/Dialog/personSelect.vue";*components:{PersonSelect}*<person-selectv-model="test"/>--><......
  • vue组件封装 - 省市县下拉选联动
    改封装组件依赖element-china-area-data插件,引入组件可参照:https://www.npmjs.com/package/element-china-area-data<!--*component:省市县下拉选联动*time:2023/7/19*author:zx*使用方式:*importDialogAddressfrom"@/components/Dialog/dialogAddress.......
  • vue项目使用vue-virtual-scroll-list虚拟滚动超多千万条数据 cv可用案例
    当我们有大量数据需要显示在列表中时,传统的滚动列表会将所有数据渲染到DOM中,导致性能下降和内存占用增加。虚拟滚动列表通过仅渲染当前视窗内可见的一小部分数据,动态地根据滚动位置更新列表内容,从而实现更高效的列表渲染。vue-virtual-scroll-list是一个用于Vue.js的虚拟滚动......
  • vue3.0 外部配置文件一 (导入json文件方式)
    vue3.0外部配置文件,重点是打包后也可以修改配置参数 注:js文件中必须是标准的json格式一、在public中创建static文件夹,在static文件夹中创建config.json  文件 config.json (必须是标准的json格式){"webSocketUrl":"ws://192.168.1.120:5011/chat/","......