public async void HandleConnection() { while (true) { var message = await Socket.ReadMessageAsync(CancellationToken.None); if (message == null) { Log.Print(LogType.Warning, "Message is null"); Disconnect(); return; } if (message.MessageType != WebSocketMessageType.Binary) { throw new NotImplementedException(); } using (var ms = new MemoryStream()) { await message.CopyToAsync(ms); await ms.FlushAsync(); var messageBytes = ms.ToArray(); Serializer.ProcessUNetMessage(messageBytes); } message.Dispose(); } }
public override async Task <Envelope> ReceiveAsync(CancellationToken cancellationToken) { EnsureIsConnected(); await _receiveSemaphore.WaitAsync(cancellationToken); try { using (var stream = await _webSocket.ReadMessageAsync(cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); if (stream == null) { return(null); } if (stream.MessageType != WebSocketMessageType.Text) { throw new NotSupportedException("An unsupported message type was received"); } using (var reader = new StreamReader(stream, Encoding.UTF8)) { var envelopeJson = await reader.ReadToEndAsync().ConfigureAwait(false); await TraceDataIfEnabledAsync(envelopeJson, DataOperation.Receive).ConfigureAwait(false); return(_envelopeSerializer.Deserialize(envelopeJson)); } } } finally { _receiveSemaphore.Release(); } }
private async void ListenForMessages(WebSocket socket) { TOP: try { if (!socket.IsConnected) return; var message = await socket.ReadMessageAsync(_tokenSource.Token); if (message != null) { using (var ms = new MemoryStream()) // length was throwing an exception { message.CopyTo(ms); var segment = new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length); var args = new DataReceivedArgs { Data = segment, SessionID = socket }; Received.Invoke(this, args); } } goto TOP; } catch (TaskCanceledException) { } catch (Exception) { goto TOP; } }
/* * Async methods are not enterely asynchronous. There are an asynchronous part and a synchronous one. * * ReadStringAsync: Awaiting a message is async (since it is unpredictable), but reading is sync since usually * messages are small, probably the data is already in the buffer. * * WriteStringAsync: Write is sync, since most of messages will be smaller than buffer size and they will be probably * cached inside the message writer or StreamWriter, but Flush is async since it is when the actual buffered message * will be written. * * These are the best settings for most of uses cases in my experience. If you have particulary large * messages and/or very slow connections, you can create your own extension like this one to fit your particular * needs. That is the reason why these methods are extensions and not part of the component. */ public static async Task <String> ReadStringAsync(this WebSocket ws, CancellationToken cancel) { using (var msg = await ws.ReadMessageAsync(cancel).ConfigureAwait(false)) { if (msg == null) { return(null); } using (var reader = new StreamReader(msg, Encoding.UTF8)) return(reader.ReadToEnd()); } }
public static async Task <string> ReadStringAsync(this WebSocket webSocket, CancellationToken cancellationToken = default(CancellationToken)) { if (webSocket == null) { throw new ArgumentNullException(nameof(webSocket)); } using (var readStream = await webSocket.ReadMessageAsync(cancellationToken).ConfigureAwait(false)) { if (readStream == null) { return(null); } using (var reader = new StreamReader(readStream, Utf8NoBom)) return(await reader.ReadToEndAsync().ConfigureAwait(false)); } }
private async void ReadSocketAsync(CancellationToken ct) { try { OnConnect?.Invoke(this, EventArgs.Empty); while (!ct.IsCancellationRequested && _listener.IsConnected) { var readStream = await _listener.ReadMessageAsync(ct).ConfigureAwait(false); if (readStream == null) { continue; // NOTE does stream need to be consumed? } using (var reader = new StreamReader(readStream, true)) { var message = await reader.ReadToEndAsync().ConfigureAwait(false); if (Trace) { Logger.DebugFormat("Socket read message: '{0}'", message); } var envelope = message.FromJson <WebSocketMessageEnvelope>(); ProcessMessageAsync(envelope, message); } } OnDisconnect?.Invoke(this, EventArgs.Empty); } catch (OperationCanceledException e) { if (Trace) { Logger.DebugFormat("Socket operation cancelled: '{0}'", e.Message); } _listener.Dispose(); _listener = null; } }
private async Task HandleWebSocketAsync(WebSocket websocket) { try { OnConnect?.Invoke(websocket); while (websocket.IsConnected) { var messageReadStream = await websocket.ReadMessageAsync(CancellationToken.None); if (messageReadStream != null) { switch (messageReadStream.MessageType) { case WebSocketMessageType.Text: using (var sr = new StreamReader(messageReadStream, Encoding.UTF8)) { var stringMessage = await sr.ReadToEndAsync(); if (!string.IsNullOrEmpty(stringMessage)) { OnPlainTextMessage?.Invoke(websocket, stringMessage); } } break; case WebSocketMessageType.Binary: using (var ms = new MemoryStream()) { await messageReadStream.CopyToAsync(ms); var data = ms.ToArray(); if (data.Length > 0) { OnEncryptedMessage?.Invoke(websocket, data); } } break; default: throw new ArgumentOutOfRangeException(); } } } OnDisconnect?.Invoke(websocket); } catch (Exception ex) { OnError?.Invoke(websocket, ex); } finally { websocket.Dispose(); } }
static async Task HandleConnectionAsync(WebSocket ws, CancellationToken token) { try { PerformanceCounters.Connected.Increment(); Byte[] buffer = new Byte[2046]; Int32 readed; IWebSocketLatencyMeasure l = ws as IWebSocketLatencyMeasure; while (ws.IsConnected && !token.IsCancellationRequested) { // await a message using (var messageReader = await ws.ReadMessageAsync(token).ConfigureAwait(false)) { if (messageReader == null) continue; // disconnection switch (messageReader.MessageType) { case WebSocketMessageType.Text: PerformanceCounters.MessagesIn.Increment(); using (var messageWriter = ws.CreateMessageWriter(WebSocketMessageType.Text)) { readed = -1; Int32 r = 0; while(readed!=0) { readed = messageReader.Read(buffer, 0, buffer.Length); if (readed != 0) { messageWriter.Write(buffer, 0, readed); r += readed; } } await messageWriter.CloseAsync(token).ConfigureAwait(false); } PerformanceCounters.MessagesOut.Increment(); break; case WebSocketMessageType.Binary: using (var messageWriter = ws.CreateMessageWriter(WebSocketMessageType.Binary)) await messageReader.CopyToAsync(messageWriter).ConfigureAwait(false); break; } } PerformanceCounters.Delay.IncrementBy(l.Latency.Ticks * Stopwatch.Frequency / 10000); PerformanceCounters.DelayBase.Increment(); } } catch (TaskCanceledException) { } catch (Exception aex) { var ex = aex.GetBaseException(); _log.Error("HandleConnectionAsync", ex); Log("Error Handling connection: " + ex.GetType().Name + ": " + ex.Message); try { ws.Close(); } catch { } } finally { ws.Dispose(); PerformanceCounters.Connected.Decrement(); } }
private async Task HandleWebSocketAsync(WebSocket websocket, ConnectionPrincipal connectionPrincipal) { VtortWebsocket soWebsocket = new VtortWebsocket(websocket, connectionPrincipal); try { Trace.TraceInformation("Server onConnect()"); connectionPrincipal.OperationMessageListener.OnConnect(soWebsocket); while (websocket.IsConnected) { var message = await websocket.ReadMessageAsync(CancellationToken.None) .ConfigureAwait(false); if (message != null) { switch (message.MessageType) { case WebSocketMessageType.Text: using (var sr = new StreamReader(message, Encoding.UTF8)) { String msgContent = await sr.ReadToEndAsync(); connectionPrincipal.OperationMessageListener.OnMessage(soWebsocket, msgContent); } break; case WebSocketMessageType.Binary: using (var ms = new MemoryStream()) { await message.CopyToAsync(ms); if (ms.Length > 0) { connectionPrincipal.OperationMessageListener.OnMessage(soWebsocket, ms.ToArray()); } } break; } } } } catch (Exception ex) { connectionPrincipal.OperationMessageListener.OnError(ex); } finally { connectionPrincipal.OperationMessageListener.OnClose(soWebsocket, 1000, ""); //Dispose before onClose is complete ??? websocket.Dispose(); } }