* LCHeartBeat.cs:

* LCConnection.cs:

* LCWebSocketClient.cs: chore: 重构连接相关结构
oneRain 2020-04-29 17:57:30 +08:00
parent d66d1e53dc
commit 1447070c8f
3 changed files with 29 additions and 52 deletions

View File

@ -43,11 +43,6 @@ namespace LeanCloud.Realtime.Internal.Connection {
/// </summary>
internal Action OnDisconnect;
/// <summary>
/// 开始重连事件
/// </summary>
internal Action OnReconnecting;
/// <summary>
/// 重连成功事件
/// </summary>
@ -73,14 +68,26 @@ namespace LeanCloud.Realtime.Internal.Connection {
responses = new Dictionary<int, TaskCompletionSource<GenericCommand>>();
heartBeat = new LCHeartBeat(this, HEART_BEAT_INTERVAL, HEART_BEAT_INTERVAL);
router = new LCRTMRouter();
client = new LCWebSocketClient(router, heartBeat) {
client = new LCWebSocketClient {
OnMessage = OnClientMessage,
OnClose = OnClientDisconnect
};
}
internal async Task Connect() {
await client.Connect();
try {
LCRTMServer rtmServer = await router.GetServer();
try {
LCLogger.Debug($"Primary Server");
await client.Connect(rtmServer.Primary);
} catch (Exception e) {
LCLogger.Error(e);
LCLogger.Debug($"Secondary Server");
await client.Connect(rtmServer.Secondary);
}
} catch (Exception e) {
throw e;
}
}
/// <summary>
@ -93,7 +100,7 @@ namespace LeanCloud.Realtime.Internal.Connection {
// 重新创建连接组件
heartBeat = new LCHeartBeat(this, HEART_BEAT_INTERVAL, HEART_BEAT_INTERVAL);
router = new LCRTMRouter();
client = new LCWebSocketClient(router, heartBeat) {
client = new LCWebSocketClient {
OnMessage = OnClientMessage,
OnClose = OnClientDisconnect
};
@ -140,12 +147,12 @@ namespace LeanCloud.Realtime.Internal.Connection {
internal async Task Close() {
OnNotification = null;
OnDisconnect = null;
OnReconnecting = null;
OnReconnected = null;
await client.Close();
}
private void OnClientMessage(byte[] bytes) {
_ = heartBeat.Refresh(OnPingTimeout);
try {
GenericCommand command = GenericCommand.Parser.ParseFrom(bytes);
LCLogger.Debug($"{id} <= {FormatCommand(command)}");
@ -178,21 +185,25 @@ namespace LeanCloud.Realtime.Internal.Connection {
}
private void OnClientDisconnect() {
heartBeat.Stop();
OnDisconnect?.Invoke();
OnReconnecting?.Invoke();
// 重连
_ = Reconnect();
}
private async void OnPingTimeout() {
await client.Close();
OnClientDisconnect();
}
private async Task Reconnect() {
OnReconnecting?.Invoke();
while (true) {
int reconnectCount = 0;
// 重连策略
while (reconnectCount < MAX_RECONNECT_TIMES) {
try {
LCLogger.Debug($"Reconnecting... {reconnectCount}");
await client.Connect();
await Connect();
break;
} catch (Exception e) {
reconnectCount++;

View File

@ -38,7 +38,7 @@ namespace LeanCloud.Realtime.Internal.Connection {
/// 更新心跳监听
/// </summary>
/// <returns></returns>
internal async Task Update(Action onTimeout) {
internal async Task Refresh(Action onTimeout) {
LCLogger.Debug("HeartBeat update");
pingCTS?.Cancel();
pongCTS?.Cancel();

View File

@ -1,8 +1,6 @@
using System;
using System.Threading.Tasks;
using System.Net.WebSockets;
using LeanCloud.Realtime.Internal.Router;
using LeanCloud.Realtime.Internal.Connection;
namespace LeanCloud.Realtime.Internal.WebSocket {
/// <summary>
@ -34,44 +32,12 @@ namespace LeanCloud.Realtime.Internal.WebSocket {
private ClientWebSocket ws;
private readonly LCRTMRouter router;
private readonly LCHeartBeat heartBeat;
internal LCWebSocketClient(LCRTMRouter router, LCHeartBeat heartBeat) {
this.router = router;
this.heartBeat = heartBeat;
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
internal async Task Connect() {
try {
LCRTMServer rtmServer = await router.GetServer();
try {
LCLogger.Debug($"Primary Server");
await Connect(rtmServer.Primary);
} catch (Exception e) {
LCLogger.Error(e);
LCLogger.Debug($"Secondary Server");
await Connect(rtmServer.Secondary);
}
} catch (Exception e) {
throw e;
}
// 接收
_ = StartReceive();
}
/// <summary>
/// 连接指定 ws 服务器
/// </summary>
/// <param name="server"></param>
/// <returns></returns>
private async Task Connect(string server) {
internal async Task Connect(string server) {
LCLogger.Debug($"Connecting WebSocket: {server}");
Task timeoutTask = Task.Delay(CONNECT_TIMEOUT);
ws = new ClientWebSocket();
@ -79,6 +45,9 @@ namespace LeanCloud.Realtime.Internal.WebSocket {
Task connectTask = ws.ConnectAsync(new Uri(server), default);
if (await Task.WhenAny(connectTask, timeoutTask) == connectTask) {
LCLogger.Debug($"Connected WebSocket: {server}");
await connectTask;
// 接收
_ = StartReceive();
} else {
throw new TimeoutException("Connect timeout");
}
@ -92,7 +61,6 @@ namespace LeanCloud.Realtime.Internal.WebSocket {
LCLogger.Debug("Closing WebSocket");
OnMessage = null;
OnClose = null;
heartBeat.Stop();
try {
// 发送关闭帧可能会很久,所以增加超时
// 主动挥手关闭,不会再收到 Close Frame
@ -152,7 +120,6 @@ namespace LeanCloud.Realtime.Internal.WebSocket {
}
}
} else if (result.MessageType == WebSocketMessageType.Binary) {
_ = heartBeat.Update(HandleExceptionClose);
// 拼合 WebSocket Message
int length = result.Count;
byte[] data = new byte[length];
@ -165,13 +132,12 @@ namespace LeanCloud.Realtime.Internal.WebSocket {
} catch (Exception e) {
// 客户端网络异常
LCLogger.Error(e);
OnClose?.Invoke();
HandleExceptionClose();
}
}
private void HandleExceptionClose() {
try {
heartBeat.Stop();
ws.Abort();
ws.Dispose();
} catch (Exception e) {