private async Task receive(ClientWebSocket socket) { var buffer = new ArraySegment <byte>(new byte[2048]); do { WebSocketReceiveResult result; using (var ms = new MemoryStream()) { do { result = await socket.ReceiveAsync(buffer, cancellationRecieveToken.Token); ms.Write(buffer.Array, buffer.Offset, result.Count); } while (!result.EndOfMessage); if (result.MessageType == WebSocketMessageType.Close) { await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken.Token); disconnectInternal(); break; } ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms, Encoding.UTF8)) { RecievedMessage?.Invoke(JObject.Parse(reader.ReadToEnd())); } } } while (true); }
public static void Listening() { // Call this function in a single thread when the client connects, then one can simply use a function like the above/below RecievedMessage += SocketConnection_RecievedMessage; if (hasStarted && Client != null && Client.Connected == true) { return; } hasStarted = true; ShouldListen = true; int err = 0; while (ShouldListen) { try { NetworkStream stream = Client.GetStream(); byte[] bytes = new byte[Client.ReceiveBufferSize]; string data = ""; stream.Read(bytes, 0, Client.ReceiveBufferSize); data = System.Text.Encoding.UTF8.GetString(bytes); foreach (var msg in data.Split('%').Where(x => !string.IsNullOrWhiteSpace(x))) { string message = msg.Substring(0, msg.IndexOf('`')); RecievedMessage?.Invoke(Client, message); } } catch (Exception ex) { err++; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.ToString()); if (err > 3) { ShouldListen = false; } } } }
private void handleRecieveMessage() { string data; NetworkStream RecieveDataStream = Client.GetStream(); byte[] bytes = new byte[256]; int i; try { while (Connected) { if ((i = RecieveDataStream.Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); RecievedMessage?.Invoke(this, data); } } } catch (Exception ex) { this.Disconnect(false); } }
// Invoke the Changed event; called whenever message recieved protected virtual void OnReceivedMessage(MyEventArgs e) { RecievedMessage?.Invoke(this, e); }