private async Task CreateAndConnectWebSocket(Uri uri) { using (var releaser = await _CommentSessionLock.LockAsync()) { if (IsConnected) { return; } if (_CommentSessionWebSocket != null) { Close(); } _CommentSessionWebSocket = new MessageWebSocket(); _CommentSessionWebSocket.Control.MessageType = SocketMessageType.Utf8; _CommentSessionWebSocket.Control.SupportedProtocols.Add("msg.nicovideo.jp#json"); _CommentSessionWebSocket.SetRequestHeader("Pragma", "not-cache"); _CommentSessionWebSocket.SetRequestHeader("Sec-WebSocket-Extensions", "permessage-deflate"); _CommentSessionWebSocket.SetRequestHeader("Sec-WebSocket-Extensions", "client_max_window_bits"); _CommentSessionWebSocket.SetRequestHeader("User-Agent", "Hohoema_UWP"); _CommentSessionWebSocket.MessageReceived += _CommentSessionWebSocket_MessageReceived; _CommentSessionWebSocket.ServerCustomValidationRequested += _CommentSessionWebSocket_ServerCustomValidationRequested; _CommentSessionWebSocket.Closed += _CommentSessionWebSocket_Closed; await _CommentSessionWebSocket.ConnectAsync(uri); _DataWriter = new DataWriter(_CommentSessionWebSocket.OutputStream); } }
public SimpleWebSocket(Uri uri, AuthenticationHeaderValue authHeader, string mediaType) : base(uri, authHeader, mediaType) { ws = new MessageWebSocket(); ws.Control.MessageType = SocketMessageType.Utf8; ws.SetRequestHeader(HttpUtil.Authorization, authHeader.Scheme + " " + authHeader.Parameter); ws.SetRequestHeader(HttpUtil.Accept, mediaType); ws.MessageReceived += ws_MessageReceived; ws.Closed += (s, args) => OnClosed(args.Reason); }
public async void OpenWebsocket(string url, List <KeyValuePair <string, string> > websocketheaders) { socket = new MessageWebSocket(); socket.Closed += (sender, args) => { Debug.Log("Stopped reason: " + args.Reason); }; socket.MessageReceived += OnWebSocketMessage; socket.Control.MessageType = SocketMessageType.Utf8; socket.ServerCustomValidationRequested += OnServerCustomValidationRequested; socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); foreach (var header in websocketheaders) { socket.SetRequestHeader(header.Key, header.Value); } await socket.ConnectAsync(new Uri(url)); messageWriter = new DataWriter(socket.OutputStream); if (OnOpen != null) { OnOpen.Invoke(); } }
public void ConfigureWebSocket(string url, List <KeyValuePair <string, string> > headers) { MessageWebSocketControl control; if (socket != null) { throw new Exception("WebSocket is already configured!"); } this.url = url; this.headers = headers; socket = new MessageWebSocket(); control = socket.Control; control.SupportedProtocols.Add("v1.eftl.tibco.com"); // to do SocketProtectionLevel to 8 (ssl tls12) uri = WebSocketUri(url); if (headers != null) { foreach (var header in headers) { socket.SetRequestHeader(header.Key, header.Value); } } }
public async Task connect() { Debug.WriteLine("WSC connect()..."); if (socket == null) { socket = new MessageWebSocket(); if (userAgent != null) { socket.SetRequestHeader("X-Signal-Agent", userAgent); } socket.MessageReceived += OnMessageReceived; socket.Closed += OnClosed; try { Uri server = new Uri(wsUri); await socket.ConnectAsync(server); if (socket != null) { attempts = 0; connected = true; } //Connected(this, EventArgs.Empty); keepAliveTimer = new Timer(sendKeepAlive, null, TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS), TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS)); messageWriter = new DataWriter(socket.OutputStream); Debug.WriteLine("WSC connected..."); Connected?.Invoke(this, EventArgs.Empty); } catch (Exception e) { /*WebErrorStatus status = WebSocketError.GetStatus(e.GetBaseException().HResult); * * switch (status) * { * case WebErrorStatus.CannotConnect: * case WebErrorStatus.NotFound: * case WebErrorStatus.RequestTimeout: * Debug.WriteLine("Cannot connect to the server. Please make sure " + * "to run the server setup script before running the sample."); * break; * * case WebErrorStatus.Unknown: * throw; * * default: * Debug.WriteLine("Error: " + status); * break; * }*/ this.connected = false; ConnectionFailed?.Invoke(this, EventArgs.Empty); Debug.WriteLine("Unable to connect WSC"); } } }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); CheckValidState(s_validConnectingStates); _messageWebSocket = new MessageWebSocket(); foreach (var header in options.RequestHeaders) { _messageWebSocket.SetRequestHeader((string)header, options.RequestHeaders[(string)header]); } string cookies = options.Cookies == null ? null : options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookies)) { _messageWebSocket.SetRequestHeader(HeaderNameCookie, cookies); } var websocketControl = _messageWebSocket.Control; foreach (var subProtocol in options.RequestedSubProtocols) { websocketControl.SupportedProtocols.Add(subProtocol); } try { _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); _closeWebSocketReceiveResultTcs = new TaskCompletionSource <WebSocketReceiveResult>(); _messageWebSocket.MessageReceived += OnMessageReceived; _messageWebSocket.Closed += OnCloseReceived; await _messageWebSocket.ConnectAsync(uri).AsTask(cancellationToken); _subProtocol = _messageWebSocket.Information.Protocol; _messageWriter = new DataWriter(_messageWebSocket.OutputStream); } catch (Exception) { UpdateState(WebSocketState.Closed); throw; } UpdateState(WebSocketState.Open); }
/// <summary> /// Prepares the WebSocket Client with the proper header and Uri for the Speech Service. /// </summary> /// <param name="authenticationToken"></param> /// <param name="region"></param> /// <returns></returns> private async Task <MessageWebSocket> InitializeSpeechWebSocketClient(string authenticationToken, string region) { // Configuring Speech Service Web Socket client header Debug.Log("Connecting to Speech Service via Web Socket."); MessageWebSocket websocketClient = new MessageWebSocket(); string connectionId = Guid.NewGuid().ToString("N"); // Make sure to change the region & culture to match your recorded audio file. string lang = "en-US"; websocketClient.SetRequestHeader("X-ConnectionId", connectionId); websocketClient.SetRequestHeader("Authorization", "Bearer " + authenticationToken); // Clients must use an appropriate endpoint of Speech Service. The endpoint is based on recognition mode and language. // The supported recognition modes are: // - interactive // - conversation // - dictation var url = ""; if (!useClassicBingSpeechService) { // New Speech Service endpoint. url = $"wss://{region}.stt.speech.microsoft.com/speech/recognition/interactive/cognitiveservices/v1?format=simple&language={lang}"; } else { // Bing Speech endpoint url = $"wss://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?format=simple&language={lang}"; } websocketClient.MessageReceived += WebSocket_MessageReceived; websocketClient.Closed += WebSocket_Closed; await websocketClient.ConnectAsync(new Uri(url)); Debug.Log("Web Socket successfully connected."); return(websocketClient); }
public NiwavidedNicoLiveCommentClient(string messageServerUrl, string threadId, string userId, HttpClient httpClient) { CommentSessionInfo = new CommentSessionInfo() { MessageServerUrl = messageServerUrl, ThreadId = threadId, UserId = userId }; _HttpClient = httpClient; _CommentSessionWebSocket = new MessageWebSocket(); _CommentSessionWebSocket.Control.MessageType = SocketMessageType.Utf8; _CommentSessionWebSocket.Control.SupportedProtocols.Add("msg.nicovideo.jp#json"); _CommentSessionWebSocket.SetRequestHeader("Pragma", "not-cache"); _CommentSessionWebSocket.SetRequestHeader("Sec-WebSocket-Extensions", "permessage-deflate"); _CommentSessionWebSocket.SetRequestHeader("Sec-WebSocket-Extensions", "client_max_window_bits"); _CommentSessionWebSocket.SetRequestHeader("User-Agent", "Hohoema_UWP"); _CommentSessionWebSocket.MessageReceived += _CommentSessionWebSocket_MessageReceived; _CommentSessionWebSocket.ServerCustomValidationRequested += _CommentSessionWebSocket_ServerCustomValidationRequested; _CommentSessionWebSocket.Closed += _CommentSessionWebSocket_Closed; }
private async static Task <bool> ConnectToWebsocket() { try { //Connect to websocket webSocket = new MessageWebSocket(); webSocket.MessageReceived += WebSocket_MessageReceived; webSocket.Closed += WebSocket_Closed; webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.Control.DesiredUnsolicitedPongInterval = TimeSpan.FromHours(1); _dataWriter = new DataWriter(webSocket.OutputStream); //webSocket.SetRequestHeader("Cookie", "wp_access_token" + "=" + token); webSocket.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134"); webSocket.SetRequestHeader("Origin", "https://discordapp.com"); //webSocket.SetRequestHeader("Cookie", "sp_landing=http%3A%2F%2Fopen.spotify.com%2Ffollow%2F1%3Furi%3Dspotify%3Aartist%3A21egYD1eInY6bGFcniCRT1%26size%3Ddetail%26theme%3Dlight; optimizelyEndUserId=oeu1520023948221r0.4129836485713321; sp_dc=AQB0T7lCVDF6amYFHwBWAMQxBSRsG3aGHoiaTrD2djHnmnEiX6QpN7WKwt9VuMSePnoyRnvVSBlidnNQUgL9mSx6; optimizelySegments=%7B%226174980032%22%3A%22search%22%2C%226176630028%22%3A%22none%22%2C%226179250069%22%3A%22false%22%2C%226161020302%22%3A%22edge%22%7D; _gid=GA1.2.599514017.1526173434; spot=%7B%22t%22%3A1520023935%2C%22m%22%3A%22uk%22%2C%22p%22%3A%22open%22%7D; _ga=GA1.2.1695017186.1519606025; wp_sso_token=AQB0T7lCVDF6amYFHwBWAMQxBSRsG3aGHoiaTrD2djHnmnEiX6QpN7WKwt9VuMSePnoyRnvVSBlidnNQUgL9mSx6; sp_t=9d1572a2db85715c17f4e623e100522e; optimizelyBuckets=%7B%7D; sp_ab=%7B%7D"); await webSocket.ConnectAsync(new Uri("wss://dealer.spotify.com/?access_token=" + spotifyToken)); IsWebSocketOpen = true; stopwatch.Start(); await App.dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(25); timer.Tick += Timer_Tick; timer.Start(); }); return(true); } catch { //websocket connection failed return(false); } }
public void Open(string url, string protocol, IDictionary <string, string> headers) { try { if (_websocket != null) { EndConnection(); } _websocket = new MessageWebSocket(); _websocket.Control.MessageType = SocketMessageType.Utf8; _websocket.Closed += _websocket_Closed; _websocket.MessageReceived += _websocket_MessageReceived; if (url.StartsWith("https")) { url = url.Replace("https://", "wss://"); } else if (url.StartsWith("http")) { url = url.Replace("http://", "ws://"); } if (headers != null) { foreach (var entry in headers) { _websocket.SetRequestHeader(entry.Key, entry.Value); } } _websocket.ConnectAsync(new Uri(url)).Completed = (source, status) => { if (status == AsyncStatus.Completed) { messageWriter = new DataWriter(_websocket.OutputStream); IsOpen = true; OnOpened(); } else if (status == AsyncStatus.Error) { OnError(new Exception("Websocket error")); } }; } catch (Exception ex) { OnError(ex); } }
public async Task TestWebSockets() { var webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += webSocket_MessageReceived; webSocket.SetRequestHeader(HttpUtil.Authorization, HttpUtil.BasicAuthHeader("admin", "test")); var uri = new Uri("ws://*****:*****@"{""cmd"":""status""}"); await writer.StoreAsync(); }
public void Open(string url, string protocol = null, string authToken = null) { try { if (_websocket != null) { EndConnection(); } _websocket = new MessageWebSocket(); _websocket.Control.MessageType = SocketMessageType.Utf8; _websocket.Closed += _websocket_Closed; _websocket.MessageReceived += _websocket_MessageReceived; if (url.StartsWith("https")) { url = url.Replace("https://", "wss://"); } else if (url.StartsWith("http")) { url = url.Replace("http://", "ws://"); } if (authToken != null) { _websocket.SetRequestHeader("Authorization", authToken); } _websocket.ConnectAsync(new Uri(url)).Completed = (source, status) => { if (status == AsyncStatus.Completed) { messageWriter = new DataWriter(_websocket.OutputStream); IsOpen = true; OnOpened(); } else if (status == AsyncStatus.Error) { OnError("Websocket error"); } }; } catch (Exception ex) { OnError(ex.Message); } }
private async void ConsolePage_Loaded(object sender, RoutedEventArgs e) { string authkey = await AttemptLogin(); string wsport = await GetPort(); consoleUri = new Uri(protocol + "://" + roamingSettings.Values["domain"] + ":" + wsport + "/", UriKind.Absolute); consoleView.ItemsSource = consoleEntries; consoleEntries.CollectionChanged += (s, args) => ScrollToBottom(); try { // Make a local copy to avoid races with Closed events. MessageWebSocket webSocket = messageWebSocket; // Have we connected yet? if (webSocket == null) { Uri server = consoleUri; webSocket = new MessageWebSocket(); webSocket.SetRequestHeader("Cookie", "loggedin" + "=" + authkey); // MessageWebSocket supports both utf8 and binary messages. // When utf8 is specified as the messageType, then the developer // promises to only send utf8-encoded data. webSocket.Control.MessageType = SocketMessageType.Utf8; // Set up callbacks webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; // Only store it after successfully connecting. messageWriter = new DataWriter(webSocket.OutputStream); } } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("Error with connecting: " + status); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } }
private async Task <bool> TryConnect() { if (SettingsService.Instance.IsLoggedIn == false) { return(false); } _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.Closed += SocketClosed; _webSocket.MessageReceived += MessageRecieved; var tokenHeader = "X-ZUMO-AUTH"; var creds = Creds.FromUserIdAndToken(SettingsService.Instance.CredUserId, SettingsService.Instance.CredToken); _webSocket.SetRequestHeader(tokenHeader, creds.Token); try { var uri = new Uri("wss://greenhouseapi.azurewebsites.net/api/Websocket"); await _webSocket.ConnectAsync(uri); _messageWriter = new DataWriter(_webSocket.OutputStream); _reconnectionAttempt = 0; LoggingService.LogInfo("Websocket connected", Windows.Foundation.Diagnostics.LoggingLevel.Information); return(true); } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); if (error == Windows.Web.WebErrorStatus.CannotConnect) { LoggingService.LogInfo($"Websocket cannot connect", Windows.Foundation.Diagnostics.LoggingLevel.Information); } else { LoggingService.LogInfo($"Websocket connection failed due to {error}, full exception: {ex.ToString()}", Windows.Foundation.Diagnostics.LoggingLevel.Warning); } _reconnectionAttempt++; CleanUp(); return(false); } }
public async Task ConnectAsync() { lock (_sync) { if (_connecting || IsConnected) { return; // already connected } _connecting = true; } try { Disconnect(); _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.Control.MaxMessageSize = MaxMessageSize; _webSocket.Closed += WebSocket_Closed; _webSocket.MessageReceived += WebSocket_MessageReceived; _webSocket.SetRequestHeader("User-Agent", "Windows Phone 10.0"); await _webSocket.ConnectAsync(new Uri("wss://rohbot.net/ws/")); IsConnected = true; } catch (Exception e) { throw new ClientException("Failed to connect to server.", e); } finally { lock (_sync) { _connecting = false; } } if (IsConnected) { Connected?.Invoke(this, EventArgs.Empty); } }
private async void InitializeInBackground(int id, string url, MessageWebSocket webSocket, JObject options) { try { var parsedOptions = new WebSocketOptions(options); if (!string.IsNullOrEmpty(parsedOptions.ProxyAddress)) { webSocket.Control.ProxyCredential = new Windows.Security.Credentials.PasswordCredential { Resource = parsedOptions.ProxyAddress, UserName = parsedOptions.UserName, Password = parsedOptions.Password }; } if (!string.IsNullOrEmpty(parsedOptions.Origin)) { webSocket.SetRequestHeader("Origin", parsedOptions.Origin); } await webSocket.ConnectAsync(new Uri(url)).AsTask().ConfigureAwait(false); _webSocketConnections.Add(id, webSocket); var dataWriter = new DataWriter(webSocket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8, }; _dataWriters.Add(id, dataWriter); SendEvent("websocketOpen", new JObject { { "id", id }, }); } catch (Exception ex) { OnError(id, ex); } }
public void ConfigureWebSocket(string url, List <KeyValuePair <string, string> > headers) { if (socket != null) { throw new Exception("WebSocket is already configured!"); } this.url = url; this.headers = headers; socket = new MessageWebSocket(); uri = WebSocketUri(url); if (headers != null) { foreach (var header in headers) { socket.SetRequestHeader(header.Key, header.Value); } } }
async void Start() { string from = FromLanguage.name; string to = ToLanguage.language; string voice = $"{Voice.locale}-{Voice.displayName}"; _apiKey = ApiKey; _speechurl = $"wss://dev.microsofttranslator.com/speech/translate?from={from}&to={to}&features=partial,texttospeech&voice={voice}&api-version=1.0"; // Retrieve the Auth token and also retrive the language support // data in parallel.. //var getTokenTask = GetTokenAsync(); //var getLanguageSupportTask = GetLanguageSupportAsync(); //await Task.WhenAll(getTokenTask, getLanguageSupportTask); //var token = getTokenTask.Result; //_languages = getLanguageSupportTask.Result; var token = await GetTokenAsync(_apiKey); Debug.Log("retrieved token is " + token); #if !UNITY_EDITOR && WINDOWS_UWP _ws = new MessageWebSocket(); _ws.SetRequestHeader("Authorization", "Bearer " + token); _ws.MessageReceived += WebSocketMessageReceived; await _ws.ConnectAsync(new Uri(_speechurl)); Debug.Log("successfully connected"); // as soon as we are connected send the WAVE header.. _dataWriter = new DataWriter(_ws.OutputStream); _dataWriter.ByteOrder = ByteOrder.LittleEndian; await WriteBytes(WavFile.GetWaveHeader(0)); _headerWritten = true; Debug.Log("Sent WAVE header"); #endif }
protected override void DoOpen() { var log = LogManager.GetLogger(Global.CallerName()); log.Info("DoOpen uri =" + this.Uri()); //How to connect with a StreamWebSocket (XAML) http://msdn.microsoft.com/en-us/library/ie/hh994398 ws = new Windows.Networking.Sockets.MessageWebSocket(); if (!string.IsNullOrEmpty(CookieHeaderValue)) { ws.SetRequestHeader("cookie", CookieHeaderValue); } ws.Control.MessageType = SocketMessageType.Utf8; ws.Closed += ws_Closed; ws.MessageReceived += ws_MessageReceived; var serverAddress = new Uri(this.Uri()); try { //await ws.ConnectAsync(serverAddress); // http://stackoverflow.com/questions/13027449/wait-for-a-thread-to-complete-in-metro //Task.WaitAny(ws.ConnectAsync(serverAddress).AsTask()); var task = ws.ConnectAsync(serverAddress).AsTask(); task.Wait(); if (task.IsFaulted) { throw new EngineIOException(task.Exception.Message, task.Exception); } ws_Opened(); } catch (Exception e) { this.OnError("DoOpen", e); } }
private async Task <bool> TryConnect() { if (Settings.Instance.IsLoggedIn == false) { return(false); } _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.Closed += SocketClosed; _webSocket.MessageReceived += MessageRecieved; var tokenHeader = "X-ZUMO-AUTH"; var creds = Creds.FromUserIdAndToken(Settings.Instance.CredUserId, Settings.Instance.CredToken); _webSocket.SetRequestHeader(tokenHeader, creds.Token); try { var uri = new Uri("wss://greenhouseapi.azurewebsites.net/api/Websocket"); await _webSocket.ConnectAsync(uri); _messageWriter = new DataWriter(_webSocket.OutputStream); _reconnectionAttempt = 0; Debug.WriteLine("Websocket connected"); return(true); } catch { Debug.WriteLine("Websocket connection failed"); _reconnectionAttempt++; CleanUp(); return(false); } }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); CheckValidState(s_validConnectingStates); _messageWebSocket = new MessageWebSocket(); foreach (var header in options.RequestHeaders) { _messageWebSocket.SetRequestHeader((string)header, options.RequestHeaders[(string)header]); } string cookies = options.Cookies == null ? null : options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookies)) { _messageWebSocket.SetRequestHeader(HeaderNameCookie, cookies); } var websocketControl = _messageWebSocket.Control; foreach (var subProtocol in options.RequestedSubProtocols) { websocketControl.SupportedProtocols.Add(subProtocol); } if (options.ClientCertificates.Count > 0) { if (!MessageWebSocketClientCertificateSupported) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703)); } X509Certificate2 dotNetClientCert = CertificateHelper.GetEligibleClientCertificate(options.ClientCertificates); if (dotNetClientCert != null) { RTCertificate winRtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(dotNetClientCert).ConfigureAwait(false); if (winRtClientCert == null) { throw new PlatformNotSupportedException(string.Format( CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore)); } websocketControl.ClientCertificate = winRtClientCert; } } // Try to opt into PartialMessage receive mode so that we can hand partial data back to the app as it arrives. // If the MessageWebSocketControl.ReceiveMode API surface is not available, the MessageWebSocket.MessageReceived // event will only get triggered when an entire WebSocket message has been received. This results in large memory // footprint and prevents "streaming" scenarios (e.g., WCF) from working properly. if (MessageWebSocketReceiveModeSupported) { // Always enable partial message receive mode if the WinRT API supports it. _messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage; } try { _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); _closeWebSocketReceiveResultTcs = new TaskCompletionSource <WebSocketReceiveResult>(); _messageWebSocket.MessageReceived += OnMessageReceived; _messageWebSocket.Closed += OnCloseReceived; await _messageWebSocket.ConnectAsync(uri).AsTask(cancellationToken).ConfigureAwait(false); _subProtocol = _messageWebSocket.Information.Protocol; _messageWriter = new DataWriter(_messageWebSocket.OutputStream); } catch (Exception) { UpdateState(WebSocketState.Closed); throw; } UpdateState(WebSocketState.Open); }
public async Task Start(long seqId, DateTimeOffset snapshotAt) { try { this.Log("Sync client starting"); if (seqId == 0) { throw new ArgumentException("Invalid seqId. Have you fetched inbox for the first time?", nameof(seqId)); } _seqId = seqId; _snapshotAt = snapshotAt; _pinging?.Cancel(); _pinging = new CancellationTokenSource(); _packetId = 1; var device = _instaApi.Device; var baseHttpFilter = new HttpBaseProtocolFilter(); var cookies = baseHttpFilter.CookieManager.GetCookies(new Uri("https://i.instagram.com")); foreach (var cookie in cookies) { var copyCookie = new HttpCookie(cookie.Name, "edge-chat.instagram.com", "/chat") { Value = cookie.Value, Expires = cookie.Expires, HttpOnly = cookie.HttpOnly, Secure = cookie.Secure }; baseHttpFilter.CookieManager.SetCookie(copyCookie); } var connectPacket = new ConnectPacket { CleanSession = true, ClientId = "mqttwsclient", HasUsername = true, HasPassword = false, KeepAliveInSeconds = 10, ProtocolLevel = 3, ProtocolName = "MQIsdp" }; var aid = GenerateDigitsRandom(16); var userAgent = $"Mozilla/5.0 (Linux; Android 10; {device.DeviceName}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.93 Mobile Safari/537.36"; var json = new JObject( new JProperty("u", _instaApi.Session.LoggedInUser.Pk), new JProperty("s", GenerateDigitsRandom(16)), new JProperty("cp", 1), new JProperty("ecp", 0), new JProperty("chat_on", true), new JProperty("fg", true), new JProperty("d", device.PhoneId.ToString()), new JProperty("ct", "cookie_auth"), new JProperty("mqtt_sid", ""), new JProperty("aid", aid), new JProperty("st", new JArray()), new JProperty("pm", new JArray()), new JProperty("dc", ""), new JProperty("no_auto_fg", true), new JProperty("a", userAgent) ); var username = JsonConvert.SerializeObject(json, Formatting.None); connectPacket.Username = username; // var buffer = StandalonePacketEncoder.EncodePacket(connectPacket); var messageWebsocket = new MessageWebSocket(); messageWebsocket.Control.MessageType = SocketMessageType.Binary; messageWebsocket.SetRequestHeader("User-Agent", userAgent); messageWebsocket.SetRequestHeader("Origin", "https://www.instagram.com"); messageWebsocket.MessageReceived += OnMessageReceived; // messageWebsocket.Closed += OnClosed; var buffer = StandalonePacketEncoder.EncodePacket(connectPacket); await messageWebsocket.ConnectAsync(new Uri("wss://edge-chat.instagram.com/chat")); await messageWebsocket.OutputStream.WriteAsync(buffer); await messageWebsocket.OutputStream.FlushAsync(); _socket = messageWebsocket; } catch (Exception e) { this.Log(e); this.Log("Failed to start"); FailedToStart?.Invoke(this, e); } }
public void Open(string url, string protocol, IDictionary <string, string> headers) { try { if (_websocket != null) { EndConnection(); } _websocket = new MessageWebSocket(); if (_isAllTrusted) { // https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.messagewebsocketcontrol#Properties // IgnorableServerCertificateErrors // introduced: Windows 10 Anniversary Edition (introduced v10.0.14393.0, // Windows.Foundation.UniversalApiContract (introduced v3) try { dynamic info = _websocket.Information; info.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); info.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); } catch (Exception ex) { Debug.WriteLine(string.Format("not supported: {0}: {1}: {2}", ex.GetType().ToString(), ex.Message, ex.StackTrace)); } } _websocket.Closed += _websocket_Closed; _websocket.MessageReceived += _websocket_MessageReceived; if (url.StartsWith("https")) { url = url.Replace("https://", "wss://"); } else if (url.StartsWith("http")) { url = url.Replace("http://", "ws://"); } if (headers != null) { foreach (var entry in headers) { _websocket.SetRequestHeader(entry.Key, entry.Value); } } _websocket.ConnectAsync(new Uri(url)).Completed = (source, status) => { if (status == AsyncStatus.Completed) { messageWriter = new DataWriter(_websocket.OutputStream); IsOpen = true; OnOpened(); } else if (status == AsyncStatus.Error) { OnError(new Exception("Websocket error")); } }; } catch (Exception ex) { OnError(ex); } }
/// <summary> /// Connect to the server before sending audio /// It will get the authentication credentials and add it to the header /// </summary> /// <param name="from">sets the launguage of source.(<see cref="SpeechLanguageInfo.Language" />)</param> /// <param name="to">sets the launguage of translated results.(<see cref="SpeechLanguageInfo.Language" />)</param> /// <param name="voice">if you get to speech of translated result, sets the value of <see cref="SpeechTtsInfo.Id" />. </param> public async Task Connect(string from, string to, string voice) { if (to == null) { throw new ArgumentNullException("to"); } if (from == null) { throw new ArgumentNullException("from"); } if (webSocket != null) { webSocket.Dispose(); webSocket = null; } if (_connectionTimer != null) { _connectionTimer.Dispose(); _connectionTimer = null; } webSocket = new MessageWebSocket(); // Get Azure authentication token var bearerToken = await RequestToken(); webSocket.SetRequestHeader("Authorization", "Bearer " + bearerToken); var query = new StringBuilder(); query.Append("from=").Append(from); query.Append("&to=").Append(to); if (!string.IsNullOrEmpty(voice)) { query.Append("&features=texttospeech&voice=").Append(voice); } query.Append("&api-version=").Append(API_VERSION); webSocket.MessageReceived += WebSocket_MessageReceived; // setup the data writer dataWriter = new DataWriter(webSocket.OutputStream); dataWriter.ByteOrder = ByteOrder.LittleEndian; dataWriter.WriteBytes(GetWaveHeader()); // connect to the service await webSocket.ConnectAsync(new Uri(SpeechTranslateUrl + query)); //// flush the dataWriter periodically _connectionTimer = new Timer(async s => { if (dataWriter.UnstoredBufferLength > 0) { await dataWriter.StoreAsync(); } // reset the timer _connectionTimer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan); }, null, TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan); }