DemoLua.cs 2.3 KB

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