/// <summary> /// 开始监听 /// </summary> /// <returns></returns> private async void StartListeningAsync() { if (_isListening) { return; } _isListening = true; while (ClientWebSocket.State == WebSocketState.Open) { byte[] serverByteArray = new byte[655300000]; ArraySegment <byte> buffer = new ArraySegment <byte>(serverByteArray); WebSocketReceiveResult wsData; try { wsData = await ClientWebSocket.ReceiveAsync(buffer, _cancellationToken); if (wsData == null) { MateralDotNettyException materalDotNettyException = new MateralDotNettyException("未获取到服务器数据"); OnException?.Invoke(materalDotNettyException); } } catch (Exception exception) { if (_isManualClose) { return; } await StopAsync(false); OnSubMessage?.Invoke("与服务器断开连接", "重要"); OnException?.Invoke(exception); OnClose?.Invoke(); _isListening = false; continue; } try { string eventJson = GetEventJson(serverByteArray, wsData); try { await HandlerMessageAsync(eventJson); } catch (Exception exception) { OnSubMessage?.Invoke("处理事件出现错误", "重要"); OnSubMessage?.Invoke(eventJson, "重要"); OnException?.Invoke(exception); } } catch (Exception exception) { OnSubMessage?.Invoke("处理事件出现错误", "重要"); OnSubMessage?.Invoke("事件数据反序列化失败", "重要"); OnException?.Invoke(exception); } } _isListening = false; }
public async Task SendCommandAsync(ICommand command) { if (ClientWebSocket.State != WebSocketState.Open) { var exception = new MateralDotNettyException("未与服务器连接,不能发送命令"); OnException?.Invoke(exception); return; } string commandJson = command.ToJson(); byte[] byteArray = _clientConfig.EncodingType.GetBytes(commandJson); var buffer = new ArraySegment <byte>(byteArray); await ClientWebSocket.SendAsync(buffer, WebSocketMessageType.Text, true, _cancellationToken); }
public async Task ReconnectionAsync() { if (_clientConfig.ReconnectionNumber > 0 && _reconnectionNumber >= _clientConfig.ReconnectionNumber) { var exception = new MateralDotNettyException($"已连接失败{_reconnectionNumber}次,请联系管理员。"); OnException?.Invoke(exception); await StopAsync(); throw exception; } if (_clientConfig.ReconnectionInterval < 1000) { throw new MateralDotNettyException("至少等待1000ms"); } if (_isManualClose) { return; } OnSubMessage?.Invoke($"[{_reconnectionNumber + 1}]WebSocketClient将在{_clientConfig.ReconnectionInterval / 1000f:N2}秒后重新连接....", "重要"); await Task.Delay(_clientConfig.ReconnectionInterval, _cancellationToken); _reconnectionNumber++; await StartAsync(); }