上海古都建筑设计集团,上海办公室装修设计公司,上海装修公司高质量的内容分享社区,上海装修公司我们不是内容生产者,我们只是上海办公室装修设计公司内容的搬运工平台

Unity Best Http插件的基本使用

guduadmin463月前

文章目录

    • 2.1 Http请求
    • 2.2 Websocket连接

      BestHTTP/2是一个HTTP/1.1和HTTP/2实现,支持几乎所有的Unity 移动和独立平台。(官网)

      2.1 Http请求

      1. 如何发送HTTP请求

      Http请求类:HTTPRequest;

      构造函数共有 8 个:

      public HTTPRequest(Uri uri);
      public HTTPRequest(Uri uri, OnRequestFinishedDelegate callback);
      public HTTPRequest(Uri uri, HTTPMethods methodType);
      public HTTPRequest(Uri uri, bool isKeepAlive, OnRequestFinishedDelegate callback);
      public HTTPRequest(Uri uri, HTTPMethods methodType, OnRequestFinishedDelegate callback);
      public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, OnRequestFinishedDelegate callback);
      public HTTPRequest(Uri uri, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback);
      public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback);
      

      HTTPRequest参数说明:

      • uri:请求的目标 URL 或 URI。
      • methodType:指定 HTTP 请求的方法类型,例如 GET、POST、PUT 等。
      • isKeepAlive:指示是否保持与服务器的连接活动状态。如果设置为 true,则在请求完成后保持连接打开;如果设置为 false,则在每个请求完成后关闭连接。
      • disableCache:指示是否禁用缓存。如果设置为 true,则禁用缓存,确保每次请求都会从服务器获取最新的数据。
      • callback:请求完成时的回调函数,可以在其中处理响应数据。

      示例:

      //创建一个 get 请求,禁用缓存并在请求完成后关闭连接,接收到返回数据时将返回数据打印到控制台
      HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1/info"), HTTPMethods.Get, false, true, (request, response) => 
              { 
                      Debug.Log(response.Data);
              }); 
      
      1. 如何携带参数

      路径参数:

      路径参数直接拼接到Uri即可;

      示例:

      int infoId = 1;
      string myUri = $"http://127.0.0.1/info/{infoId}";
      HTTPRequest request = new HTTPRequest(new Uri(myUri), HTTPMethods.Get); 
      

      请求参数:

      使用AddField进行添加,AddField有两个参数,参数一是fieldName,参数二是value;

      示例:

      HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Post, OnRequestFinished);
      request.AddField("username", "admin");
      request.AddField("password", "123456");
      

      请求头参数:

      使用AddHeader进行添加请求头,和AddField类似AddHeader也是两个参数,参数一是name,参数二是value;

      示例:

      var request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Get, OnRequestFinished);
      request.AddHeader("Authorization", "mytoken");
      

      请求体参数:

      HTTPRequest的实例的RawData属用于存放请求体请求体

      // 将JSON数据序列化为字符串
      var jsonData = "{\"username\":\"admin\",\"password\":\"123456\""}";
      // 将字符串编码为UTF-8字节数组
      var bytes = System.Text.Encoding.UTF8.GetBytes(jsonData);
      // 创建请求并将字节数组作为请求体发送
      var request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Post, OnRequestFinished);
      request.RawData = bytes;
      request.AddHeader("Content-Type", "application/json");
      request.Send();
      

      2.2 Websocket连接

      1. 创建
      WebSocket webSocket = new WebSocket(new Uri("ws://127.0.0.1/webSocket")); 
      
      1. 生命周期事件

      OnOpen事件:在建立与服务器的连接时调用。

      • 当连接建立成功后,会触发该事件,并将WebSocket对象传递给OnWebSocketOpen方法。。

        OnMessage事件:从服务器收到文本消息时调用。

        • 当从服务器接收到文本消息时,会触发该事件,并将WebSocket对象和消息内容传递给OnMessageReceived方法。

          OnBinary事件:从服务器收到二进制blob消息时调用。

          • 当从服务器接收到二进制消息时,会触发该事件,并将WebSocket对象和消息字节数组传递给OnBinaryMessageReceived方法。

            OnClosed事件:在客户端或服务器关闭连接时调用,或发生内部错误。

            • 当连接关闭时,会触发该事件,并将WebSocket对象、关闭代码和关闭消息传递给OnWebSocketClosed方法。

              OnError事件:当无法连接到服务器、发生内部错误或连接丢失时调用。

              • 当发生错误时,会触发该事件,并将WebSocket对象和异常对象传递给OnError方法。
      1. 通信方法

      Open:建立连接;

      Send:发送消息到服务器;

      Close:断开连接;

      示例:

      /// 
      /// websocket客户端
      /// 
      public class WebSocketClient : SingletonManager
      {
          private static readonly object padlock = new object();
          
          /// 
      	/// websocket客户端实例
      	/// 
          protected static WebSocketClient instance;
          /// 
      	/// 获取单例
      	/// 
          public static WebSocketClient getInst()
          {
           	if (instance == null)
              {
              	lock (padlock)
                  {
                   	if (instance == null)
                       {
                       	instance = new WebSocketClient();
                       }
                  }
              }
                  return instance;
          }
          
          private WebSocket webSocket;
          /// 
          /// 连接初始化
          /// 
          public void init(long pid)
          {
              string url = GlobalConstant.WEBSOCKET_PATH + pid;
              webSocket = new WebSocket(new Uri(url));
              webSocket.OnOpen += OnWebSocketOpen;
              webSocket.OnMessage += OnMessageReceived;
              webSocket.OnBinary += OnBinaryMessageReceived;
              webSocket.OnClosed += OnWebSocketClosed;
              webSocket.OnError += OnError;
              webSocket.Open();
          }
          /// 
          /// 服务器字符串消息
          /// 
          /// 
          /// 
          protected void OnMessageReceived(WebSocket webSocket, string message)
          {
              //Debug.Log("Text Message received from server: " + message);
          }
          /// 
          /// 连接回调
          /// 
          /// 
          protected void OnWebSocketOpen(WebSocket webSocket)
          {
              Debug.Log("WebSocket Open!");
          }
          /// 
          /// 服务器二进制消息
          /// 
          /// 
          /// 
          protected void OnBinaryMessageReceived(WebSocket webSocket, byte[] bytes)
          {
              WsResult result = ProtoBufUtil.Deserialize(bytes);
              if (result.status.code != 200)
              {
                  Debug.Log(result.status.code);
                  Debug.Log(result.status.msg);
                  return;
              }
              if (result.status.code == 200)
              {
                  AnalysisUtils.getProxy()[result.sendType](bytes);
              }
          }
          /// 
          /// 关闭连接回调
          /// 
          /// 
          /// 
          /// 
          protected void OnWebSocketClosed(WebSocket webSocket, UInt16 code, string message)
          {
              Debug.Log("WebSocket Closed!");
          }
          /// 
          /// 错误通知
          /// 
          /// 
          /// 
          protected void OnError(WebSocket ws, string ex)
          {
              string errorMsg = string.Empty;
              if (ws.InternalRequest.Response != null)
              {
                  errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
              }
              Debug.Log("An error occured: " + (ex != null ? ex : "Unknown: " + errorMsg));
          }
          /// 
          /// 发送字符串: 
          /// 
          /// 
          public void OnSend(string msg)
          {
              webSocket.Send(msg);
          }
          /// 
          /// 发送二进制流: 
          /// 
          /// 
          public void OnSend(byte[] buffer)
          {
              webSocket.Send(buffer);
          }
          /// 
          /// 断开连接
          /// 
          public void OnClose()
          {
              webSocket.Close();
          }
      }
      

      上一章 【Unity DOTween插件常用方法(二)】

网友评论

搜索
最新文章
热门文章
热门标签
 
 做梦梦到坟墓是什么意思  周易全文  梦见鸡蛋破了是什么意思