Unity WebSocket建立长链接

首先需要用到 Best HTTP (Pro) 插件   链接:https://download.csdn.net/download/qq_43912395/19791052

直接上代码,里面已经包含了注释

using BestHTTP.WebSocket;
using UnityEngine;
using System;
using BestHTTP.WebSocket.Frames;
using LitJson;

public class WebSocket2 : MonoBehaviour {

    private static WebSocket2 instance;

    public static WebSocket webSocket;

    public static string tempMsg = "";

    public static WebSocket2 GetInstance()
    {
        if (instance == null) {

            Debug.LogError("instance为空");

            instance = new GameObject("WebSocket2").AddComponent();

            instance.Init();

            DontDestroyOnLoad(instance.gameObject);
        }
        return instance;
    }

    private void Awake()
    {
        instance = this;
        DontDestroyOnLoad(instance.gameObject);
    }

    public static bool IsExist {
        get
        {
            return (instance != null);
        }
    }

    bool IsInit = false;

    private void Start()
    {
        Init();
    }

    private void Init()
    {
        if (!IsInit) {
            IsInit = true;

            Debug.Log(" ssssss   " + GVars.payIp + ":" + GVars.payPort);
            webSocket = new WebSocket(new Uri("ws://" + GVars.payIp + ":" + GVars.payPort));
            webSocket.OnOpen += OnOpen;
            webSocket.OnMessage += OnMessageReceived;
            webSocket.OnError += OnError;
            webSocket.OnClosed += OnClosed;
            webSocket.OnBinary += Onbinary;
            webSocket.OnErrorDesc += OnErrorDesc;
            webSocket.OnIncompleteFrame += OnIncompleteFrame;


            webSocket.Open();

            if (tempMsg != "" && webSocket != null) {
                Debug.LogError("重新发送: " + tempMsg);
                webSocket.Send(tempMsg);
            }

            Debug.Log("初始化[已打开]");
        }
    }

    //反初始化
    private void AntiInit()
    {
        Debug.Log("反初始化");

        // SystemData.IsLogin = false;

        if (webSocket != null) {
            webSocket.Close();

            webSocket.OnOpen = null;
            webSocket.OnMessage = null;
            webSocket.OnError = null;
            webSocket.OnClosed = null;
            webSocket.OnBinary = null;
            webSocket.OnErrorDesc = null;
            webSocket.OnIncompleteFrame = null;

            webSocket = null;
        }

        //重新初始化
#if UNITY_EDITOR

#elif UNITY_ANDROID || UNITY_IPHONE

        IsInit = false;


#endif

        Init();

    }

    /// 
    /// 主动建立连接
    /// 
    public void Connect()
    {

        AntiInit();
    }

    /// 
    /// 主动关闭连接 
    /// 
    public void CloseConnect()
    {

        webSocket.Close();
    }

    //切换开关
    public void SwitchServer()
    {
        Debug.Log(GVars.payIp);
        AntiInit();
    }

    //断开
    public void DisConnectServer()
    {
        if (webSocket != null) {
            webSocket.Close();
        }
    }

    /// 
    ///  已进行 在编译的 可直接发送【指定格式 MsgCtn】
    /// 
    public void SendMsg(int type, byte[] data)
    {
        //MsgCtn send = new MsgCtn
        //{
        //    Type = type,
        //    ReqMsgId = SystemData.playerdata.id,
        //    Datas = ByteString.CopyFrom(data),
        //};

        //int size = send.CalculateSize();
        //byte[] RoomByte = new byte[size];
        //var stream = new CodedOutputStream(RoomByte);
        //send.WriteTo(stream);


        //SendMsg(RoomByte);
    }

    /// 
    /// 已进行 在编译的 可直接发送
    /// 
    public void SendMsg(string msg)
    {

        if (webSocket == null) {
            IsInit = false;
            Init();
            webSocket.Open();
        }

        Debug.LogError("发送数据: " + msg);
        tempMsg = msg;
        webSocket.Send(msg);
    }

    /// 
    /// 已进行 在编译的 可直接发送
    /// 
    public void SendMsg(byte[] data)
    {
        byte[] PwdByte = BitConverter.GetBytes(29099);
        byte[] SendBytes = new byte[data.Length + PwdByte.Length];

        PwdByte.CopyTo(SendBytes, 0);
        data.CopyTo(SendBytes, PwdByte.Length);

        if (webSocket == null) {
            IsInit = false;
            Init();
            webSocket.Open();
        }

        WebSocketFrame frame = new WebSocketFrame(webSocket, WebSocketFrameTypes.Binary, SendBytes);

        webSocket.Send(frame);
    }



    //建立连接
    private void OnOpen(WebSocket webSocket)
    {
        Debug.Log("长连接连接成功!");
    }

    private void OnApplicationQuit()
    {
        webSocket.Close();
    }

    //关闭连接
    private void OnClosed(WebSocket webSocket, ushort code, string message)
    {
        Debug.Log("断开连接" + code + ":" + message);
        if (webSocket != null) {
            AntiInit();
        }
    }


    //接收错误
    private void OnError(WebSocket webSocket, Exception ex)
    {
        string errorMsg = string.Empty;
#if !UNITY_WEBGL || UNITY_EDITOR
        if (webSocket.InternalRequest.Response != null)
            errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", webSocket.InternalRequest.Response.StatusCode, webSocket.InternalRequest.Response.Message);

        Debug.Log(errorMsg);
#endif

        if (webSocket != null) {

            AntiInit();
        }
    }

    //接收消息
    private void OnMessageReceived(WebSocket webSocket, string message)
    {

        JsonData jd = JsonMapper.ToObject(message);

        Debug.LogError("接收到消息 JD: " + jd.ToJson());       

    }

    private void OnIncompleteFrame(WebSocket webSocket, WebSocketFrameReader frame)
    {
        
        Debug.Log("接收到消息:");
    }

    private void OnErrorDesc(WebSocket webSocket, string reason)
    {
        Debug.Log("接收到消息:" + reason);
    }

    private void Onbinary(WebSocket webSocket, byte[] data)
    {
        //Debug.Log("接收到消息:" + LitJson.JsonMapper.ToJson(data));

        byte[] PwdByte = BitConverter.GetBytes(124512);

        byte[] ss = new byte[PwdByte.Length];

        Array.Copy(data, ss, ss.Length);

        //Debug.Log(BitConverter.ToInt32(ss, 0));

        if (BitConverter.ToInt32(ss, 0) == 124512) {
            byte[] NewData = new byte[data.Length - ss.Length];

            Array.Copy(data, ss.Length, NewData, 0, NewData.Length);

        }
        else {
            Debug.Log("接收到未加密的错误信息【无法解析】");
            DisConnectServer();
            try {
                Debug.Log(LitJson.JsonMapper.ToJson(data));
            }
            catch (Exception) {

            }


        }
    }
}

你可能感兴趣的:(websocket,socket,unity)