DemoSimple.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using UnityEngine;
  10. using ZLog;
  11. public class DemoSimple : MonoBehaviour
  12. {
  13. //string m_Ip = "192.168.0.121";
  14. //string m_Ip = "8.134.36.175";
  15. //int m_Port = 9305;
  16. string m_Ip = "192.168.0.55";
  17. int m_Port = 9206;
  18. float reconnectTime = 0;
  19. private void Start()
  20. {
  21. // 设置日志的Level,屏蔽Socket的部分日志。设到2以下,查看所有日志
  22. Options.Instance.LogLevel = 3;
  23. //Log.Verbose = false;
  24. // 在主线程初始化ZLog
  25. Log.Debug("");
  26. // 连接服务器
  27. SimpleSocketManager.Connect(m_Ip, m_Port);
  28. // 发送心跳包消息的测试
  29. StartCoroutine(SendLoop());
  30. }
  31. private void Update()
  32. {
  33. if (SimpleSocketManager.Update() != ZSocket.ErrorCode.ERR_Success)
  34. {
  35. // 发生错误,重连处理
  36. if (Time.time > reconnectTime)
  37. {
  38. Debug.LogError($"Demo Reconnect ErrorCode: {SimpleSocketManager.ErrorCode}");
  39. SimpleSocketManager.Connect(m_Ip, m_Port);
  40. reconnectTime = Time.time + 1f;
  41. }
  42. }
  43. }
  44. private void OnDestroy()
  45. {
  46. // 断开与服务器的连接
  47. SimpleSocketManager.Disconnect();
  48. }
  49. IEnumerator SendLoop()
  50. {
  51. int i = 1;
  52. //while (i > 0)
  53. while (true)
  54. {
  55. i--;
  56. for (int j = 0; j < 1; ++j)
  57. {
  58. // 发送不需要回复的消息
  59. //Debug.Log($"Demo Send {SimpleSocketManager.ErrorCode}");
  60. //SimpleSocketManager.Send( "HEARTBEAT", @"{""ping"":true}");
  61. // 发送需要回复的RPC消息,结果通过回调获取
  62. Debug.Log($"Demo Rpc {SimpleSocketManager.ErrorCode}");
  63. SimpleSocketManager.Call("HEARTBEAT_REQ", @"{""ping"":true}", (err, msg) =>
  64. {
  65. if (err != ZSocket.ErrorCode.ERR_Success)
  66. {
  67. Debug.LogError($"Demo Rpc Error: {err} {msg}");
  68. return;
  69. }
  70. Debug.Log($"Demo Recv {msg}");
  71. });
  72. }
  73. yield return new WaitForSeconds(10f);
  74. //yield return new WaitForEndOfFrame();
  75. }
  76. }
  77. }