Unity3D使用WebSocket通信相关实现

基于Unity3D通过WebSocket进行通信,传输数据

一、导入插件

点击链接https://download.csdn.net/download/Z_ning/12535526进行下载、解压后导入unity中

二、相关脚本代码

  1. 这里我创建了DataMagnage脚本
  2. 引入头文件(我这里是直接粘贴我项目中的代码、引入了其他的头文件,不需要的头文件呈灰色删掉就好)
    using System;
    using System.Text;
    using UnityEngine;
    using UnityEngine.UI;
    using BestHTTP.WebSocket;
    using System.Collections.Generic;
    using Newtonsoft.Json.Linq;
    using System.Collections;
    using System.Threading;

     

  3. 相关连接、初始化以及接收数据、关闭、抛出异常代码

    /// <summary>
        /// --------------------这是需要连接的URL地址
        /// </summary>
        public string url = "ws://localhost:8080//websocket/";
     
        private WebSocket webSocket;
     
        private void Init()
        {
            webSocket = new WebSocket(new Uri(url));
            webSocket.OnOpen += OnOpen;
            webSocket.OnMessage += OnMessageReceived;
            webSocket.OnError += OnError;
            webSocket.OnClosed += OnClosed;    
        }
     
        private void AntiInit()
        {
            webSocket.OnOpen = null;
            webSocket.OnMessage = null;
            webSocket.OnError = null;
            webSocket.OnClosed = null;
            webSocket = null;
        }
    
        public void Connect()
        {
            webSocket.Open();
            print("发送连接");
        }
    
        private byte[] getBytes(string message)
        {
            byte[] buffer = Encoding.Default.GetBytes(message);
            return buffer;
        }
        public void Send(string str)
        {
            webSocket.Send(str);
        }
    
        public void Close()
        {
            webSocket.Close();
        }
        void OnOpen(WebSocket ws)
        {
            Debug.Log("连接成功");     
            
        }
       /// <summary>
        /// 接收信息
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="msg">接收内容</param>
        void OnMessageReceived(WebSocket ws,string msg)
        {
            Debug.Log(msg);
            SetLog(msg);
        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        void OnClosed(WebSocket ws, UInt16 code, string message)
        {
            Debug.Log(message);
            setConsoleMsg(message);
            antiInit();
            init();
        }
    
        private void OnDestroy()
        {
            if (webSocket != null && webSocket.IsOpen)
            {
                webSocket.Close();
                antiInit();
            }
        }
       
        /// <summary>
        /// Called when an error occured on client side
        /// </summary>
        void OnError(WebSocket ws, Exception ex)
        {
            string errorMsg = string.Empty;
    #if !UNITY_WEBGL || UNITY_EDITOR
            if (ws.InternalRequest.Response != null)
                errorMsg = string.Format("Status Code from Server: {0} and Message: {1}",      ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
    #endif
            Debug.Log(errorMsg);
            setConsoleMsg(errorMsg);
            antiInit();
            init();
        }
  4. 然后就是调用方法,如果直接在进入场景后调用就把init();Connect();两个方法写在Start()里面就行了。

三、总结

我是直接在我项目中将相关代码粘出来的、就不再写Demo了。

注意:

建议把该脚本和BestHTTP文件夹放在一起,不然可能会报错……

posted @ 2020-06-19 17:38  爱吃肉肉的小姑凉  阅读(1829)  评论(0)    收藏  举报