当前位置:   article > 正文

Unity3D WebGL平台使用WebSocket通信的方法和示例_unitywebsocket

unitywebsocket

      之前在WebGL平台和服务端交互的时候使用的是UnityWebRequest,通过WebAPI的方式进行交互,后来发现可以用WebSocket交互后就果断换了WebSocket。

一、Unity3D客户端

我在Unity端使用的是NativeWebSocket

NativeWebSocket下载地址

直接导入Unity即可,

下面是适配的代码,直接挂载在GameObject。

 

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using NativeWebSocket;
  7. using LitJson;
  8. public class Connection : MonoBehaviour
  9. {
  10. WebSocket websocket;
  11. public Text textLog;
  12. async void Start()
  13. {
  14. websocket = new WebSocket("ws://127.0.0.1:7181");
  15. websocket.OnOpen += () =>
  16. {
  17. Debug.Log("Connection open!");
  18. // textLog.text = $"Connection open! {Time.realtimeSinceStartup} \n {textLog.text}";
  19. };
  20. websocket.OnError += (e) =>
  21. {
  22. Debug.Log("Error! " + e);
  23. // textLog.text = $"Error:{e} {Time.realtimeSinceStartup} \n {textLog.text}";
  24. };
  25. websocket.OnClose += (e) =>
  26. {
  27. Debug.Log("Connection closed!");
  28. // textLog.text = $"Connection closed! {Time.realtimeSinceStartup} \n {textLog.text}";
  29. };
  30. websocket.OnMessage += (bytes) =>
  31. {
  32. // Debug.Log("OnMessage!");
  33. //textLog.text = $"OnMessage! {Time.realtimeSinceStartup} \n {textLog.text}";
  34. // Debug.Log(bytes);
  35. // getting the message as a string
  36. var message = System.Text.Encoding.Default.GetString(bytes);
  37. textLog.text = $"消息内容:{message} ";
  38. Debug.Log("OnMessage! " + message);
  39. //SocketData Sdata= JsonMapper.ToObject<SocketData>(message);
  40. var Sdata=JsonMapper.ToObject< Dictionary<string, string>>(message);
  41. Debug.Log(Sdata["data"]);
  42. string b = Sdata["data"];
  43. byte[] bs= Convert.FromBase64String(b);
  44. var m = System.Text.Encoding.Default.GetString(bs);
  45. Debug.Log(m);
  46. };
  47. // Keep sending messages at every 0.3s
  48. // InvokeRepeating("SendWebSocketMessage", 0.0f, 2f);
  49. // waiting for messages
  50. await websocket.Connect();
  51. }
  52. void Update()
  53. {
  54. #if !UNITY_WEBGL || UNITY_EDITOR
  55. websocket.DispatchMessageQueue();
  56. #endif
  57. }
  58. async void SendWebSocketMessage()
  59. {
  60. if (websocket.State == WebSocketState.Open)
  61. {
  62. // Sending bytes
  63. await websocket.Send(new byte[] { 10, 20, 30 });
  64. // Sending plain text
  65. await websocket.SendText("plain text message");
  66. }
  67. }
  68. private async void OnApplicationQuit()
  69. {
  70. await websocket.Close();
  71. }
  72. }

二、服务端

运行后可与客户端交互

下载地址

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/107293
推荐阅读
相关标签
  

闽ICP备14008679号