Unity WebSocket客户端重连尝试后协程无法启动问题排查
问题原因
WebSocketSharp的OnError和OnClose回调是在非Unity主线程中触发的,而Unity的StartCoroutine必须在主线程调用,否则协程根本不会启动——这就是你看不到ReconnectCoroutine日志的核心原因。
修复方案
你需要把重连请求切换到Unity主线程执行,最简单的方式是维护一个主线程任务队列,在Update里处理队列中的任务。
修改后的代码示例:
using System.Collections; using System.Collections.Concurrent; using UnityEngine; using WebSocketSharp; public class WebSocketClient : MonoBehaviour { private WebSocket ws; public Configurations config; private int reconnectAttempt = 0; // 主线程任务队列 private ConcurrentQueue<System.Action> mainThreadTasks = new ConcurrentQueue<System.Action>(); void Start() { ConnectToServer(); } void Update() { // 处理主线程任务 while (mainThreadTasks.TryDequeue(out var task)) { task.Invoke(); } } void ConnectToServer() { ws = new WebSocket(config.serverAddress); ws.OnOpen += (sender, e) => { Debug.Log("Connected."); // 连接成功重置重连次数 reconnectAttempt = 0; }; // 回调里只把任务丢进主线程队列,不直接执行重连逻辑 ws.OnError += (sender, e) => mainThreadTasks.Enqueue(AttemptReconnect); ws.OnClose += (sender, e) => mainThreadTasks.Enqueue(AttemptReconnect); ws.Connect(); } void AttemptReconnect() { if (reconnectAttempt < config.maxReconnectAttempts) { reconnectAttempt++; Debug.Log($"Reconnect attempt {reconnectAttempt}/{config.maxReconnectAttempts}"); StartCoroutine(ReconnectCoroutine()); } else { Debug.LogError("Max reconnect attempts reached."); } } private IEnumerator ReconnectCoroutine() { Debug.Log("Starting ReconnectCoroutine"); yield return new WaitForSeconds(config.reconnectDelay); Debug.Log("Reconnect Delay passed"); ConnectToServer(); } void OnDestroy() { ws?.Close(); } }
额外注意点
- 连接成功后记得重置
reconnectAttempt,否则下次断开会直接从之前的次数继续计数。 - 确保
config.reconnectDelay是正数,避免协程直接跳过等待逻辑。 - 确认自定义的
Configurations类中,serverAddress、maxReconnectAttempts、reconnectDelay都已正确赋值。
内容的提问来源于stack exchange,提问作者Tim Hoerner
相关产品推荐
相关产品推荐

