当前位置:   article > 正文

Unity热更新方案C#Like(十七)-详解支持的长链接Socket和WebSocket_unity 实现长链接

unity 实现长链接

C#Like是Unity的热更方案,使用纯C#语言写出可以热更新的代码,就像可以在所有平台使用DLL(动态链接库)文件一样.遵从KISS设计原则,让用户轻松构建或升级成Unity的热更新项目.

简介

本篇主要介绍C#Like支持的长链接Socket和WebSocket,免费版和完整版都支持,示范代码差别在于完整版的使用了自定义get/set和使用了switch语句.

  • Socket: 对应内置的类CSL_ClientSocket
  • WebSocket: 对应内置的类CSL_ClientWebSocket
  • 注意在WebGL平台下只支持WebSocket,如果你的应用包含WebGL平台,必须包含WebSocket,如示范代码一样使用.

这里仅示范客户端的主接口代码,更加详尽的用法详见 Unity热更新方案C#Like(廿一)-详解KissFrameworkServer:对应的示范例子和官网所用的服务器框架

C#Like免费版:

示范代码如下:

  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace CSharpLike
  4. {
  5. /// <summary>
  6. /// 如何使用Socket和WebSocket的示范.
  7. /// 所有的函数均在主线程内运行.
  8. /// </summary>
  9. public class SampleSocket
  10. {
  11. /// <summary>
  12. /// 使用WebSocket还是Socket.
  13. /// WebGL将强制使用WebSocket!
  14. /// 你应该调用ampleSocket.Instance前设置它.
  15. /// </summary>
  16. public static bool usingWebSocket = false;
  17. /// <summary>
  18. /// WebSocket的URI(支持WSS).
  19. /// 你应该调用ampleSocket.Instance前设置它.
  20. /// </summary>
  21. public static string webSocketURI = "ws://127.0.0.1:9000";
  22. /// <summary>
  23. /// Socket的Host.
  24. /// 你应该调用ampleSocket.Instance前设置它.
  25. /// </summary>
  26. public static string socketHost = "127.0.0.1";
  27. /// <summary>
  28. /// Socket的端口.
  29. /// 你应该调用ampleSocket.Instance前设置它.
  30. /// </summary>
  31. public static int socketPort = 9001;
  32. /// <summary>
  33. /// RSA公钥,使用Socket的情况下.
  34. /// 你应该调用SampleSocket.Instance前设置它.
  35. /// 你在Unity编辑器里的C#Like设置面板点击'Generate RSA'按钮后,
  36. /// 你可以在Assets/C#Like/Editor/RSAPublicKey.txt找到.
  37. /// 如果你不想使用安全模式,你可以设置为空白.
  38. /// 安全模式:先通过RSA发送AES密码到服务器,然后客户端和服务器之间使用AES加密传输.
  39. /// </summary>
  40. public static string socketRSAPublicKey = "";
  41. /// <summary>
  42. /// WebSocket/Socket对象.
  43. /// 在使用它之前, 你应该先设置
  44. /// usingWebSocket/webSocketURI/socketHost/socketPort的值
  45. /// </summary>
  46. public static SampleSocket Instance
  47. {
  48. get;
  49. set;
  50. }
  51. /// <summary>
  52. /// 初始化SampleSocket对象,你必须先初始化它,因为免费版不支持自定义get/set
  53. /// </summary>
  54. public static void Init()
  55. {
  56. if (Instance == null)
  57. Instance = new SampleSocket();
  58. }
  59. /// <summary>
  60. /// WebSocket/Socket是否已连接.
  61. /// </summary>
  62. public bool IsConnected()
  63. {
  64. if (clientWebSocket != null)
  65. return clientWebSocket.IsConnected;
  66. else if (clientSocket != null)
  67. return clientSocket.IsConnected;
  68. return false;
  69. }
  70. /// <summary>
  71. /// 当WebSocket/Socket连接上后的事件
  72. /// </summary>
  73. void OnOpen()
  74. {
  75. Debug.Log("SampleSocket:OnOpen");
  76. }
  77. /// <summary>
  78. /// 当WebSocket/Socket关闭后的事件
  79. /// </summary>
  80. void OnClose(string msg)
  81. {
  82. Debug.Log("SampleSocket:OnClose:" + msg);
  83. }
  84. /// <summary>
  85. /// 当WebSocket/Socket发生错误的事件
  86. /// </summary>
  87. void OnError(string msg)
  88. {
  89. //just print the message
  90. Debug.LogError("SampleSocket:OnError:" + msg);
  91. }
  92. public SampleSocket()
  93. {
  94. Debug.Log("Application.platform=" + Application.platform);
  95. //WebGL平台只支持WebSocket
  96. if (usingWebSocket || Application.platform == RuntimePlatform.WebGLPlayer)
  97. {
  98. Debug.Log("usingWebSocket=true");
  99. //初始化WebSocket
  100. GameObject go = new GameObject("ClientWebSocket");
  101. clientWebSocket = go.AddComponent<CSL_ClientWebSocket>();
  102. //设置WebSocket的回调
  103. clientWebSocket.onOpen += OnOpen;
  104. clientWebSocket.onClose += OnClose;
  105. clientWebSocket.onError += OnError;
  106. clientWebSocket.onMessage += OnMessage;
  107. //设置Uri
  108. clientWebSocket.SetUri(webSocketURI);
  109. 开始连接到服务器
  110. //clientWebSocket.Connect();
  111. }
  112. else
  113. {
  114. Debug.Log("usingWebSocket=false");
  115. //初始化Socket
  116. GameObject go = new GameObject("ClientSocket");
  117. clientSocket = go.AddComponent<CSL_ClientSocket>();
  118. //设置Socket的回调
  119. clientSocket.onOpen += OnOpen;
  120. clientSocket.onClose += OnClose;
  121. clientSocket.onError += OnError;
  122. clientSocket.onMessage += OnMessage;
  123. clientSocket.Host = socketHost;
  124. clientSocket.Port = socketPort;
  125. clientSocket.RSAPublicKey = socketRSAPublicKey;
  126. 开始连接到服务器
  127. //clientSocket.Connect();
  128. }
  129. }
  130. /// <summary>
  131. /// 关闭当前WebSocket/Socket的连接
  132. /// </summary>
  133. public void Close()
  134. {
  135. if (clientWebSocket != null)
  136. clientWebSocket.Close();
  137. else if (clientSocket != null)
  138. clientSocket.Close();
  139. else
  140. Debug.LogError("SampleSocket : Close : clientWebSocket and clientSocket are both null.");
  141. }
  142. /// <summary>
  143. /// 连接WebSocket/Socket
  144. /// </summary>
  145. public void Connect()
  146. {
  147. if (clientWebSocket != null)
  148. clientWebSocket.Connect();
  149. else if (clientSocket != null)
  150. clientSocket.Connect();
  151. else
  152. Debug.LogError("SampleSocket : Connect : clientWebSocket and clientSocket are both null.");
  153. }
  154. /// <summary>
  155. /// 发送JSON对象到服务器
  156. /// </summary>
  157. /// <param name="jsonData">将要发到服务器的JSON对象</param>
  158. public void Send(JSONData jsonData)
  159. {
  160. if (clientWebSocket != null)
  161. clientWebSocket.Send(jsonData);
  162. else if (clientSocket != null)
  163. clientSocket.Send(jsonData);
  164. else
  165. Debug.LogError("SampleSocket : Send : clientWebSocket and clientSocket are both null.");
  166. }
  167. /// <summary>
  168. /// 收到服务器的JSON对象
  169. /// </summary>
  170. /// <param name="jsonData">服务器发过来的JSON对象</param>
  171. void OnMessage(JSONData jsonData)
  172. {
  173. if (Application.isEditor)
  174. Debug.Log("SampleSocket : OnMessage : " + jsonData.ToJson(true));
  175. //这里处理不同的命令
  176. //int packetType = jsonData["packetType"];//如果设置JSONData.packetIsInteger为true
  177. string packetType = jsonData["packetType"];
  178. //免费版不能使用枚举,我们采用字符串.
  179. //免费版不能使用switch语句,我们使用if-else代替,如果类型很多的话会有性能问题
  180. if (packetType == "CB_Error")
  181. {
  182. Debug.LogError(jsonData["error"]);//我们这里打印一个错误信息
  183. }
  184. else if (packetType == "CB_Tips")
  185. {
  186. Debug.Log(jsonData["tips"]);//我们这里打印一个提示信息
  187. }
  188. else
  189. {
  190. Debug.LogError("SampleSocket : OnMessage : Unknown packetType : " + packetType);
  191. }
  192. }
  193. /// <summary>
  194. /// 销毁WebSocket/Socket对象
  195. /// </summary>
  196. public void Destroy()
  197. {
  198. if (clientWebSocket != null)
  199. GameObject.Destroy(clientWebSocket.gameObject);
  200. else if (clientSocket != null)
  201. GameObject.Destroy(clientSocket.gameObject);
  202. clientWebSocket = null;
  203. clientSocket = null;
  204. Instance = null;
  205. }
  206. CSL_ClientWebSocket clientWebSocket = null;
  207. CSL_ClientSocket clientSocket = null;
  208. }
  209. }

 C#Like完整版:

示范代码如下:

  1. using UnityEngine;
  2. namespace CSharpLike
  3. {
  4. /// <summary>
  5. /// 如何使用Socket和WebSocket的示范.
  6. /// 所有的函数均在主线程内运行.
  7. /// </summary>
  8. public class SampleSocket
  9. {
  10. /// <summary>
  11. /// 使用WebSocket还是Socket.
  12. /// WebGL将强制使用WebSocket!
  13. /// 你应该调用ampleSocket.Instance前设置它.
  14. /// </summary>
  15. public static bool usingWebSocket = false;
  16. /// <summary>
  17. /// WebSocket的URI(支持WSS).
  18. /// 你应该调用ampleSocket.Instance前设置它.
  19. /// </summary>
  20. public static string webSocketURI = "ws://127.0.0.1:9000";
  21. /// <summary>
  22. /// Socket的Host.
  23. /// 你应该调用ampleSocket.Instance前设置它.
  24. /// </summary>
  25. public static string socketHost = "127.0.0.1";
  26. /// <summary>
  27. /// Socket的端口.
  28. /// 你应该调用ampleSocket.Instance前设置它.
  29. /// </summary>
  30. public static int socketPort = 9001;
  31. /// <summary>
  32. /// RSA公钥,使用Socket的情况下.
  33. /// 你应该调用SampleSocket.Instance前设置它.
  34. /// 你在Unity编辑器里的C#Like设置面板点击'Generate RSA'按钮后,
  35. /// 你可以在Assets/C#Like/Editor/RSAPublicKey.txt找到.
  36. /// 如果你不想使用安全模式,你可以设置为空白.
  37. /// 安全模式:先通过RSA发送AES密码到服务器,然后客户端和服务器之间使用AES加密传输.
  38. /// </summary>
  39. public static string socketRSAPublicKey = "";
  40. /// <summary>
  41. /// WebSocket/Socket对象.
  42. /// 在使用它之前, 你应该先设置
  43. /// usingWebSocket/webSocketURI/socketHost/socketPort的值
  44. /// </summary>
  45. public static SampleSocket Instance
  46. {
  47. get
  48. {
  49. if (mInstance == null)
  50. mInstance = new SampleSocket();
  51. return mInstance;
  52. }
  53. }
  54. /// <summary>
  55. /// WebSocket/Socket是否已连接.
  56. /// </summary>
  57. public bool IsConnected
  58. {
  59. get
  60. {
  61. if (clientWebSocket != null)
  62. return clientWebSocket.IsConnected;
  63. else if (clientSocket != null)
  64. return clientSocket.IsConnected;
  65. return false;
  66. }
  67. }
  68. /// <summary>
  69. /// 当WebSocket/Socket连接上后的事件
  70. /// </summary>
  71. void OnOpen()
  72. {
  73. Debug.Log("SampleSocket:OnOpen");
  74. }
  75. /// <summary>
  76. /// 当WebSocket/Socket关闭后的事件
  77. /// </summary>
  78. void OnClose(string msg)
  79. {
  80. Debug.Log("SampleSocket:OnClose:" + msg);
  81. }
  82. /// <summary>
  83. /// 当WebSocket/Socket发生错误的事件
  84. /// </summary>
  85. void OnError(string msg)
  86. {
  87. //just print the message
  88. Debug.LogError("SampleSocket:OnError:" + msg);
  89. }
  90. public SampleSocket()
  91. {
  92. Debug.Log("Application.platform=" + Application.platform);
  93. //WebGL平台只支持WebSocket
  94. if (usingWebSocket || Application.platform == RuntimePlatform.WebGLPlayer)
  95. {
  96. Debug.Log("usingWebSocket=true");
  97. //初始化WebSocket
  98. GameObject go = new GameObject("ClientWebSocket");
  99. clientWebSocket = go.AddComponent<CSL_ClientWebSocket>();
  100. //设置WebSocket的回调
  101. clientWebSocket.onOpen += OnOpen;
  102. clientWebSocket.onClose += OnClose;
  103. clientWebSocket.onError += OnError;
  104. clientWebSocket.onMessage += OnMessage;
  105. //设置Uri
  106. clientWebSocket.SetUri(webSocketURI);
  107. 开始连接到服务器
  108. //clientWebSocket.Connect();
  109. }
  110. else
  111. {
  112. Debug.Log("usingWebSocket=false");
  113. //初始化Socket
  114. GameObject go = new GameObject("ClientSocket");
  115. clientSocket = go.AddComponent<CSL_ClientSocket>();
  116. //设置Socket的回调
  117. clientSocket.onOpen += OnOpen;
  118. clientSocket.onClose += OnClose;
  119. clientSocket.onError += OnError;
  120. clientSocket.onMessage += OnMessage;
  121. clientSocket.Host = socketHost;
  122. clientSocket.Port = socketPort;
  123. clientSocket.RSAPublicKey = socketRSAPublicKey;
  124. 开始连接到服务器
  125. //clientSocket.Connect();
  126. }
  127. }
  128. /// <summary>
  129. /// 关闭当前WebSocket/Socket的连接
  130. /// </summary>
  131. public void Close()
  132. {
  133. if (clientWebSocket != null)
  134. clientWebSocket.Close();
  135. else if (clientSocket != null)
  136. clientSocket.Close();
  137. else
  138. Debug.LogError("SampleSocket : Close : clientWebSocket and clientSocket are both null.");
  139. }
  140. /// <summary>
  141. /// 连接WebSocket/Socket
  142. /// </summary>
  143. public void Connect()
  144. {
  145. if (clientWebSocket != null)
  146. clientWebSocket.Connect();
  147. else if (clientSocket != null)
  148. clientSocket.Connect();
  149. else
  150. Debug.LogError("SampleSocket : Connect : clientWebSocket and clientSocket are both null.");
  151. }
  152. /// <summary>
  153. /// 发送JSON对象到服务器
  154. /// </summary>
  155. /// <param name="jsonData">将要发到服务器的JSON对象</param>
  156. public void Send(JSONData jsonData)
  157. {
  158. if (clientWebSocket != null)
  159. clientWebSocket.Send(jsonData);
  160. else if (clientSocket != null)
  161. clientSocket.Send(jsonData);
  162. else
  163. Debug.LogError("SampleSocket : Send : clientWebSocket and clientSocket are both null.");
  164. }
  165. /// <summary>
  166. /// 收到服务器的JSON对象
  167. /// </summary>
  168. /// <param name="jsonData">服务器发过来的JSON对象</param>
  169. void OnMessage(JSONData jsonData)
  170. {
  171. if (Application.isEditor)
  172. Debug.Log("SampleSocket : OnMessage : " + jsonData.ToJson(true));
  173. //这里处理不同的命令
  174. switch ((PacketType)jsonData.GetPacketType(typeof(PacketType)))
  175. {
  176. case PacketType.CB_Error:
  177. Debug.LogError(jsonData["error"]);//我们这里打印一个错误信息
  178. break;
  179. case PacketType.CB_Tips:
  180. Debug.Log(jsonData["tips"]);//我们这里打印一个提示信息
  181. break;
  182. default:
  183. Debug.LogError("SampleSocket : OnMessage : Unknown packetType : " + jsonData["packetType"]);
  184. break;
  185. }
  186. }
  187. /// <summary>
  188. /// 销毁WebSocket/Socket对象
  189. /// </summary>
  190. public void Destroy()
  191. {
  192. if (clientWebSocket != null)
  193. GameObject.Destroy(clientWebSocket.gameObject);
  194. else if (clientSocket != null)
  195. GameObject.Destroy(clientSocket.gameObject);
  196. clientWebSocket = null;
  197. clientSocket = null;
  198. mInstance = null;
  199. }
  200. static SampleSocket mInstance;
  201. CSL_ClientWebSocket clientWebSocket = null;
  202. CSL_ClientSocket clientSocket = null;
  203. }
  204. }

 本系列文章导读:

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

闽ICP备14008679号