private async Task <string> ReceiveMessageAsync(WebSocket ws) { byte[] buffer = new byte[bufferSize]; WebSocketReceiveResult result = await ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); if (result.CloseStatus.HasValue) { return(null); } return(StringsConverter.getString(buffer)); }
/// <summary> /// Send and receives one message /// </summary> /// <param name="messageToSend"></param> /// <returns>Received message</returns> public async Task <string> SendAndReceive(string messageToSend) { //var messageString = Shared var messageBuffer = StringsConverter.getBytes(messageToSend, 1024); Console.WriteLine("Siunciama zinute " + messageToSend); await _ws.SendAsync(messageBuffer, WebSocketMessageType.Text, true, _cts.Token); await _ws.ReceiveAsync(messageBuffer, CancellationToken.None); return(StringsConverter.getString(messageBuffer.Array)); }
public async Task ReceiveMessages() { byte[] buffer = new byte[BufferSize]; WebSocketReceiveResult received; try { while (!_cts.IsCancellationRequested) { received = await _ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); if (received.CloseStatus.HasValue) { break; } string messageText = StringsConverter.getString(buffer); _gameFacade.OnMessageReceived(messageText); ClearBytes(buffer); } } catch (Exception ex) { var innerMessage = ex.InnerException != null ? "\n Inner message: \n" + ex.InnerException.ToString() : string.Empty; Console.WriteLine(ex.Message + innerMessage); throw; } finally { //close web socket? if (_ws.State != WebSocketState.Closed) { await _ws.CloseAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None); } } }