| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using UnityEngine;
- using ZLog;
- public class DemoLua : MonoBehaviour
- {
- string m_Ip = "192.168.0.55";
- int m_Port = 9205;
- float reconnectTime = 0;
- private void Start()
- {
- // 设置日志的Level,屏蔽Socket的部分日志。设到2以下,查看所有日志
- Options.Instance.LogLevel = 3;
- //Log.Verbose = false;
- // 在主线程初始化ZLog
- Log.Debug("");
- // 连接服务器
- SimpleSocketManager.Connect(m_Ip, m_Port);
- // 发送心跳包消息的测试
- StartCoroutine(SendLoop());
- }
- private void Update()
- {
- if (SimpleSocketManager.Update() != ZSocket.ErrorCode.ERR_Success)
- {
- // 发生错误,重连处理
- if (Time.time > reconnectTime)
- {
- Debug.LogError($"Demo Reconnect ErrorCode: {SimpleSocketManager.ErrorCode}");
- SimpleSocketManager.Connect(m_Ip, m_Port);
- reconnectTime = Time.time + 1f;
- }
- }
- }
- private void OnDestroy()
- {
- // 断开与服务器的连接
- SimpleSocketManager.Disconnect();
- }
- IEnumerator SendLoop()
- {
- int i = 1;
- //while (i > 0)
- while (true)
- {
- i--;
- for (int j = 0; j < 1; ++j)
- {
- // 发送不需要回复的消息
- //Debug.Log($"Demo Send {SimpleSocketManager.ErrorCode}");
- //SimpleSocketManager.Send( "HEARTBEAT", @"{""ping"":true}");
- // 发送需要回复的RPC消息,结果通过回调获取
- Debug.Log($"Demo Rpc {SimpleSocketManager.ErrorCode}");
- SimpleSocketManager.Call("HEARTBEAT_REQ", @"{""ping"":true}", (err, msg) =>
- {
- if (err != ZSocket.ErrorCode.ERR_Success)
- {
- Debug.LogError($"Demo Rpc Error: {err} {msg}");
- return;
- }
- Debug.Log($"Demo Recv {msg}");
- });
- }
- yield return new WaitForSeconds(10f);
- //yield return new WaitForEndOfFrame();
- }
- }
- }
|