public async Task Connect() { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; var cts = new CancellationToken(); socket = new ClientWebSocket(); try { await socket.ConnectAsync(serverUri, cts); } catch { Debug.Print("error on connection establish"); return; } var ctss = new CancellationTokenSource(); Task.Factory.StartNew( async() => { var rcvBytes = new byte[128]; var rcvBuffer = new ArraySegment <byte>(rcvBytes); while (true) { WebSocketReceiveResult rcvResult = null; try { rcvResult = await socket.ReceiveAsync(rcvBuffer, ctss.Token); } catch { Debug.Print("error on communication"); socket = null; break; } try { byte[] msgBytes = rcvBuffer.Skip(rcvBuffer.Offset).Take(rcvResult.Count).ToArray(); string rcvMsg = Encoding.UTF8.GetString(msgBytes); Application.Current.Dispatcher.Invoke(new System.Action(() => { HandleMessage(rcvMsg); })); } catch (Exception e) { Debug.Print(e.ToString()); } } }, ctss.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); await SendRequest(MediaCommand.Join(Room)); }
public async Task SendRequest(MediaCommand cmd) { await SendString(cmd.ToJson()); }