Unity Web Socket
369 0
实名

通过了实名认证的内容创造者

发布于 2022-8-23 11:22:35

您需要 登录 才可以下载或查看,没有账号?注册

x
用于WebGL平台的Unity WebSocket插件
  1. // 命名空间
  2. using UnityWebSocket;

  3. // 创建实例
  4. string address = "ws://echo.websocket.org";
  5. WebSocket socket = new WebSocket(address);

  6. // 注册回调
  7. socket.OnOpen += OnOpen;
  8. socket.OnClose += OnClose;
  9. socket.OnMessage += OnMessage;
  10. socket.OnError += OnError;

  11. // 连接
  12. socket.ConnectAsync();

  13. // 发送 string 类型数据
  14. socket.SendAsync(str);

  15. // 或者 发送 byte[] 类型数据(建议使用)
  16. socket.SendAsync(bytes);

  17. // 关闭连接
  18. socket.CloseAsync();
点击此处复制文本
  1. using UnityEngine;

  2. namespace UnityWebSocket.Demo
  3. {
  4.     public class UnityWebSocketDemo : MonoBehaviour
  5.     {
  6.         public string address = "wss://echo.websocket.events";
  7.         public string sendText = "Hello UnityWebSocket!";

  8.         private IWebSocket socket;

  9.         private bool logMessage = true;
  10.         private string log = "";
  11.         private int sendCount;
  12.         private int receiveCount;
  13.         private Vector2 scrollPos;
  14.         private Color green = new Color(0.1f, 1, 0.1f);
  15.         private Color red = new Color(1f, 0.1f, 0.1f);
  16.         private Color wait = new Color(0.7f, 0.3f, 0.3f);

  17.         private void OnGUI()
  18.         {
  19.             var scale = Screen.width / 800f;
  20.             GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(scale, scale, 1));
  21.             var width = GUILayout.Width(Screen.width / scale - 10);

  22.             WebSocketState state = socket == null ? WebSocketState.Closed : socket.ReadyState;

  23.             GUILayout.BeginHorizontal();
  24.             GUILayout.Label("SDK Version: " + Settings.VERSION, GUILayout.Width(Screen.width / scale - 100));
  25.             GUI.color = green;
  26.             GUILayout.Label([        DISCUZ_CODE_1        ]quot;FPS: {fps:F2}", GUILayout.Width(80));
  27.             GUI.color = Color.white;
  28.             GUILayout.EndHorizontal();

  29.             GUILayout.BeginHorizontal();
  30.             GUILayout.Label("State: ", GUILayout.Width(36));
  31.             GUI.color = WebSocketState.Closed == state ? red : WebSocketState.Open == state ? green : wait;
  32.             GUILayout.Label([        DISCUZ_CODE_1        ]quot;{state}", GUILayout.Width(120));
  33.             GUI.color = Color.white;
  34.             GUILayout.EndHorizontal();

  35.             GUI.enabled = state == WebSocketState.Closed;
  36.             GUILayout.Label("Address: ", width);
  37.             address = GUILayout.TextField(address, width);

  38.             GUILayout.BeginHorizontal();
  39.             GUI.enabled = state == WebSocketState.Closed;
  40.             if (GUILayout.Button(state == WebSocketState.Connecting ? "Connecting..." : "Connect"))
  41.             {
  42.                 socket = new WebSocket(address);
  43.                 socket.OnOpen += Socket_OnOpen;
  44.                 socket.OnMessage += Socket_OnMessage;
  45.                 socket.OnClose += Socket_OnClose;
  46.                 socket.OnError += Socket_OnError;
  47.                 AddLog(string.Format("Connecting..."));
  48.                 socket.ConnectAsync();
  49.             }

  50.             GUI.enabled = state == WebSocketState.Open;
  51.             if (GUILayout.Button(state == WebSocketState.Closing ? "Closing..." : "Close"))
  52.             {
  53.                 AddLog(string.Format("Closing..."));
  54.                 socket.CloseAsync();
  55.             }
  56.             GUILayout.EndHorizontal();

  57.             GUILayout.Label("Message: ");
  58.             sendText = GUILayout.TextArea(sendText, GUILayout.MinHeight(50), width);

  59.             GUILayout.BeginHorizontal();
  60.             if (GUILayout.Button("Send") && !string.IsNullOrEmpty(sendText))
  61.             {
  62.                 socket.SendAsync(sendText);
  63.                 AddLog(string.Format("Send: {0}", sendText));
  64.                 sendCount += 1;
  65.             }
  66.             if (GUILayout.Button("Send Bytes") && !string.IsNullOrEmpty(sendText))
  67.             {
  68.                 var bytes = System.Text.Encoding.UTF8.GetBytes(sendText);
  69.                 socket.SendAsync(bytes);
  70.                 AddLog(string.Format("Send Bytes ({1}): {0}", sendText, bytes.Length));
  71.                 sendCount += 1;
  72.             }
  73.             if (GUILayout.Button("Send x100") && !string.IsNullOrEmpty(sendText))
  74.             {
  75.                 for (int i = 0; i < 100; i++)
  76.                 {
  77.                     var text = (i + 1).ToString() + ". " + sendText;
  78.                     socket.SendAsync(text);
  79.                     AddLog(string.Format("Send: {0}", text));
  80.                     sendCount += 1;
  81.                 }
  82.             }
  83.             if (GUILayout.Button("Send Bytes x100") && !string.IsNullOrEmpty(sendText))
  84.             {
  85.                 for (int i = 0; i < 100; i++)
  86.                 {
  87.                     var text = (i + 1).ToString() + ". " + sendText;
  88.                     var bytes = System.Text.Encoding.UTF8.GetBytes(text);
  89.                     socket.SendAsync(bytes);
  90.                     AddLog(string.Format("Send Bytes ({1}): {0}", text, bytes.Length));
  91.                     sendCount += 1;
  92.                 }
  93.             }

  94.             GUILayout.EndHorizontal();

  95.             GUI.enabled = true;
  96.             GUILayout.BeginHorizontal();
  97.             logMessage = GUILayout.Toggle(logMessage, "Log Message");
  98.             GUILayout.Label(string.Format("Send Count: {0}", sendCount));
  99.             GUILayout.Label(string.Format("Receive Count: {0}", receiveCount));
  100.             GUILayout.EndHorizontal();

  101.             if (GUILayout.Button("Clear"))
  102.             {
  103.                 log = "";
  104.                 receiveCount = 0;
  105.                 sendCount = 0;
  106.             }

  107.             scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.MaxHeight(Screen.height / scale - 270), width);
  108.             GUILayout.Label(log);
  109.             GUILayout.EndScrollView();
  110.         }

  111.         private void AddLog(string str)
  112.         {
  113.             if (!logMessage) return;
  114.             if (str.Length > 100) str = str.Substring(0, 100) + "...";
  115.             log += str + "\n";
  116.             if (log.Length > 22 * 1024)
  117.             {
  118.                 log = log.Substring(log.Length - 22 * 1024);
  119.             }
  120.             scrollPos.y = int.MaxValue;
  121.         }

  122.         private void Socket_OnOpen(object sender, OpenEventArgs e)
  123.         {
  124.             AddLog(string.Format("Connected: {0}", address));
  125.         }

  126.         private void Socket_OnMessage(object sender, MessageEventArgs e)
  127.         {
  128.             if (e.IsBinary)
  129.             {
  130.                 AddLog(string.Format("Receive Bytes ({1}): {0}", e.Data, e.RawData.Length));
  131.             }
  132.             else if (e.IsText)
  133.             {
  134.                 AddLog(string.Format("Receive: {0}", e.Data));
  135.             }
  136.             receiveCount += 1;
  137.         }

  138.         private void Socket_OnClose(object sender, CloseEventArgs e)
  139.         {
  140.             AddLog(string.Format("Closed: StatusCode: {0}, Reason: {1}", e.StatusCode, e.Reason));
  141.         }

  142.         private void Socket_OnError(object sender, ErrorEventArgs e)
  143.         {
  144.             AddLog(string.Format("Error: {0}", e.Message));
  145.         }

  146.         private void OnApplicationQuit()
  147.         {
  148.             if (socket != null && socket.ReadyState != WebSocketState.Closed)
  149.             {
  150.                 socket.CloseAsync();
  151.             }
  152.         }

  153.         private int frame = 0;
  154.         private float time = 0;
  155.         private float fps = 0;
  156.         private void Update()
  157.         {
  158.             frame += 1;
  159.             time += Time.deltaTime;
  160.             if (time >= 0.5f)
  161.             {
  162.                 fps = frame / time;
  163.                 frame = 0;
  164.                 time = 0;
  165.             }
  166.         }
  167.     }
  168. }
点击此处复制文本
image.png

还没有设置签名!您可以在此展示你的链接,或者个人主页!
使用道具 <
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表