Vue WebSocket的实现 含断线重连

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

}
}

 

posted @ 2023-07-24 17:24  海乐学习  阅读(1576)  评论(0编辑  收藏  举报