/// <inheritdoc /> public async Task ConnectAsync(ISession session, CancellationToken ct = default(CancellationToken), bool appearOnline = false, int connectTimeout = 5000) { if (_listener != null) { await _listener.CloseAsync(); _messageReplies.Clear(); _listener.Dispose(); _listener = null; } var addr = new UriBuilder(_baseUri) { Path = "/ws", Query = string.Concat("lang=en&status=", appearOnline, "&token=", session.AuthToken) }; var timeoutTask = Task.Delay(TimeSpan.FromMilliseconds(connectTimeout), ct); var connectTask = _client.ConnectAsync(addr.Uri, ct); // Limit time (msec) allowed for connect attempts. if (await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false) == timeoutTask) { throw new TimeoutException($"Socket connect timed out after '{connectTimeout}' milliseconds."); } _listener = await connectTask.ConfigureAwait(false); ReadSocketAsync(ct); WriteSocketAsync(ct); }
private static async Task EchoAllIncomingMessagesAsync(WebSocket webSocket, CancellationToken cancellation) { Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' connected."); var sw = new Stopwatch(); try { while (webSocket.IsConnected && !cancellation.IsCancellationRequested) { try { var messageText = await webSocket.ReadStringAsync(cancellation).ConfigureAwait(false); if (messageText == null) { break; // webSocket is disconnected } Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' recived: " + messageText + "."); sw.Restart(); messageText = WebSocketHandler(messageText); await webSocket.WriteStringAsync(messageText, cancellation).ConfigureAwait(false); Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' sent: " + messageText + "."); sw.Stop(); } catch (TaskCanceledException) { break; } catch (Exception readWriteError) { Console.WriteLine("An error occurred while reading/writing echo message.", readWriteError); await webSocket.CloseAsync().ConfigureAwait(false); } } } finally { webSocket.Dispose(); Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' disconnected."); } }