/// <summary> /// Connect to remote server async. Retries to connect <see cref="ReconnectTryCount"/> times if server is unavailable. (Implementation of <see cref="IConnectable"/>) /// </summary> public async Task ConnectAsync() { if (Connected) { return; } try { await ConnectInternalAsync(); } catch (SocketException ex) { _open = false; OnConnectionException?.Invoke(new EstablishConnectionException(ex)); } }
/// <summary> /// Connect to remote server. Retries to connect <see cref="ReconnectTryCount"/> times if server is unavailable. (Implementation of <see cref="IConnectable"/>) /// </summary> public void Connect() { if (Connected) { return; } try { ConnectInternal(); OnConnected?.Invoke(); } catch (SocketException ex) { _open = false; OnConnectionException?.Invoke(new EstablishConnectionException(ex)); } }
private async Task <int> RetrySendAction(Func <Task <int> > sendAction, Func <Task> connectAction) { try { return(await sendAction()); } catch (SocketException ex) { try { Close(); await connectAction(); await Task.Delay(100); return(await sendAction()); } catch (SocketException sex) { OnConnectionException?.Invoke(new SendMessageConnectionException(ex)); } } return(-1); }
private void ReceivePacket(object sender, SocketAsyncEventArgs e) { if (e.BytesTransferred == 0) { Close(); OnConnectionException?.Invoke(new ReceiveMessageConnectionException(new SocketException())); return; } var token = e.UserToken as EventArgsToken; token.SetRate(e.BytesTransferred); var totalReceived = e.Offset + e.BytesTransferred; if (totalReceived >= e.Buffer.Length) { if (token.ReadHeader) {//extract message size from envelope header and start receiving actual payload var buffer = e.Buffer; if (BitConverter.IsLittleEndian) { Array.Reverse(buffer); } var messageLength = BitConverter.ToInt32(buffer, 0); ReceiveLoop(messageLength, false); } else { //restart loop for new messages ReceiveLoop(); try { //whole payload was received, pass it to handler OnReceive?.Invoke(new ReceiveContext { Payload = e.Buffer, Rate = token.Rate, ReceiveDuration = token.ReceiveDuration }); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } } } else {//didn't get full message, continue receiving token.ChunkTimestamp = DateTime.UtcNow.Ticks; e.UserToken = token; e.SetBuffer(e.Buffer, totalReceived, e.Buffer.Length - totalReceived); if (!_socket.ReceiveAsync(e)) { ReceivePacket(this, e); } } }
protected void InvokeOnConnectionException() { OnConnectionException?.Invoke(); }