public async Task ConnectAsync(Guid sessionId) { socket = new MessageWebSocket(); socket.MessageReceived += OnSocketMessageReceived; socket.Closed += OnSocketClosed; try { await socket.ConnectAsync(hostUri); State = CommunicationServiceState.EstablishConnection; await SendPacketAsync(socket.OutputStream.AsStreamForWrite(), new HelloPacket { SessionId = sessionId }); State = CommunicationServiceState.Connected; } catch (WebException exception) { State = CommunicationServiceState.Failed; var status = WebSocketError.GetStatus(exception.HResult); Debug.WriteLine("Error: {0}", status); } }
private void HandleOnMessage(object sender, MessageWebSocketMessageReceivedEventArgs args) { if (OnMessage == null) { return; } try { using (var reader = args.GetDataReader()) { if (args.MessageType == SocketMessageType.Utf8) { string text = reader.ReadString(reader.UnconsumedBufferLength); OnMessage.Invoke(sender, new WebSocketMessageEventArgs(text)); } else if (args.MessageType == SocketMessageType.Binary) { byte[] data = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(data); OnMessage.Invoke(sender, new WebSocketMessageEventArgs(data)); } } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); RaiseError(status.ToString() + " " + ex.Message); } }
public Task SendMessageAsync(string text) { if (CommunicationServiceState.Connected != State) { return(Task.CompletedTask); } try { var packet = new PublishMessagePacket { Message = text }; return(SendPacketAsync(socket.OutputStream.AsStreamForWrite(), packet)); } catch (WebException exception) { State = CommunicationServiceState.Failed; var status = WebSocketError.GetStatus(exception.HResult); Debug.WriteLine("Error: {0}", status); return(Task.CompletedTask); } }
public Task QueryTimeAsync() { if (CommunicationServiceState.Connected != State) { return(Task.CompletedTask); } try { var packet = new CommandPacket { Command = Command.QueryTime }; return(SendPacketAsync(socket.OutputStream.AsStreamForWrite(), packet)); } catch (WebException exception) { State = CommunicationServiceState.Failed; var status = WebSocketError.GetStatus(exception.HResult); Debug.WriteLine("Error: {0}", status); return(Task.CompletedTask); } }
public Task SetNameAsync(string name) { if (CommunicationServiceState.Connected != State) { return(Task.CompletedTask); } try { var packet = new UpdateProfileRequestPacket { UserName = name }; return(SendPacketAsync(socket.OutputStream.AsStreamForWrite(), packet)); } catch (WebException exception) { State = CommunicationServiceState.Failed; var status = WebSocketError.GetStatus(exception.HResult); Debug.WriteLine("Error: {0}", status); return(Task.CompletedTask); } }
public async void ConnectAsync() { if (socket == null) { Debug.Log("Configure MessageWebSocket"); ConfigureWebSocket(url, headers); } AttachHandlers(); try { await socket.ConnectAsync(uri); dataWriter = new DataWriter(socket.OutputStream); isOpened = true; RaiseOpen(); } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); if (status.Equals(WebErrorStatus.Unknown)) { Debug.LogError("An unknown WebErrorStatus exception occurred."); } else { RaiseError("Error: MessageWebSocket failed to connect: " + status.ToString()); } } }
/// <summary>A best-effor sender of data</summary> /// <param name="toSend"></param> /// <returns></returns> public async Task <bool> SendAsync(object toSend) { var jsonData = JsonConvert.SerializeObject(toSend); if ((ConnectionState)Interlocked.Read(ref _connectionState) != ConnectionState.Connected) { return(false); } else if (_messageWriter == null) { return(false); } try { // Send the data as one complete message. _messageWriter.WriteString(jsonData); await _messageWriter.StoreAsync(); return(true); } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); LoggingService.LogInfo($"Error while sending websocket data, {error}, full exception:{ex.ToString()}", Windows.Foundation.Diagnostics.LoggingLevel.Warning); CleanUp(); return(false); } }
internal static async Task <string> DownloadChangesFor(Core.Models.Addon addon) { if (string.IsNullOrEmpty(addon.ProjectUrl)) { Debug.WriteLine("No project url found"); return(string.Empty); } if (!NetworkInterface.GetIsNetworkAvailable()) { Debug.WriteLine("No Internet connection available"); return(string.Empty); } var uri = GetChangeLogUri(addon); try { var htmlPage = await Http.WebHttpClient.GetStringAsync(uri); if (string.IsNullOrEmpty(htmlPage)) { return(string.Empty); } // Debug.WriteLine("changes: " + htmlPage); return(ParsedPage(addon, htmlPage)); } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); Debug.WriteLine("[ERROR] DownloadChangesFor " + uri + " " + error); return(string.Empty); } }
private static async Task<List<Download>> FromElvUI(Addon addon) { var uri = new Uri(addon.ProjectUrl); try { var htmlPage = await Http.WebHttpClient.GetStringAsync(uri); var fresh = Parse.FromPageToDownloads(addon, htmlPage); return fresh.Except(addon.Downloads).ToList(); } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); if (error == Windows.Web.WebErrorStatus.Unknown) { Debug.WriteLine("[ERROR] DownloadVersionsFor " + uri + " " + ex.Message); } else { Debug.WriteLine("[ERROR] DownloadVersionsFor " + uri + " " + error); } } return new List<Download>(); }
public async void SendString(string data) { try { socket.Control.MessageType = SocketMessageType.Utf8; messageWriter.WriteString(data); await messageWriter.StoreAsync(); } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.OperationCanceled: Debug.LogError("Background write canceled."); break; default: Debug.LogError("Error: " + status); Debug.LogError(ex.Message); break; } } }
private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { System.Diagnostics.Debug.WriteLine("Message Received; Type: " + args.MessageType); using (DataReader reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string read = reader.ReadString(reader.UnconsumedBufferLength); //Convert to JSON if (read != "") { } System.Diagnostics.Debug.WriteLine(read); } } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); if (status == WebErrorStatus.Unknown) { throw; } // Normally we'd use the status to test for specific conditions we want to handle specially, // and only use ex.Message for display purposes. In this sample, we'll just output the // status for debugging here, but still use ex.Message below. System.Diagnostics.Debug.WriteLine("Error: " + status); System.Diagnostics.Debug.WriteLine(ex.Message); } }
private void Stop_Click(object sender, RoutedEventArgs e) { try { if (streamWebSocket != null) { rootPage.NotifyUser("Stopping", NotifyType.StatusMessage); streamWebSocket.Close(1000, "Closed due to user request."); streamWebSocket = null; } else { rootPage.NotifyUser("There is no active socket to stop.", NotifyType.StatusMessage); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); if (status == WebErrorStatus.Unknown) { throw; } // Normally we'd use the status to test for specific conditions we want to handle specially, // and only use ex.Message for display purposes. In this sample, we'll just output the // status for debugging here, but still use ex.Message below. rootPage.NotifyUser("Error: " + status, NotifyType.ErrorMessage); OutputField.Text += ex.Message + "\r\n"; } }
private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { MarshalText(OutputField, "Message Received; Type: " + args.MessageType + "\r\n"); using (DataReader reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string read = reader.ReadString(reader.UnconsumedBufferLength); MarshalText(OutputField, read + "\r\n"); } } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); if (status == WebErrorStatus.Unknown) { throw; } // Normally we'd use the status to test for specific conditions we want to handle specially, // and only use ex.Message for display purposes. In this sample, we'll just output the // status for debugging here, but still use ex.Message below. MarshalText(OutputField, "Error: " + status + "\r\n"); MarshalText(OutputField, ex.Message + "\r\n"); } }
/// <summary> /// Handler for received message. /// Associated with Websocket. /// </summary> private void ReceivedMessage(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { // Use a datareader to read the message // out of the websocket args. using (DataReader dataReader = args.GetDataReader()) { dataReader.UnicodeEncoding = UnicodeEncoding.Utf8; string wrapped = dataReader.ReadString(dataReader.UnconsumedBufferLength); SignallerMessage unwrapped = this.MessageProtocol.UnwrapMessage(wrapped); this.MessageHandlers[(string)unwrapped.Type]?.Invoke(this, unwrapped); } } catch (Exception ex) { Windows.Web.WebErrorStatus webErrorStatus = WebSocketError.GetStatus ( ex.GetBaseException().HResult ); System.Diagnostics.Debug.WriteLine(ex.ToString()); this.IsConnected = false; this.ConnectionFailedUIHandler?.Invoke(this, EventArgs.Empty); } }
protected override void OnNavigatedTo(NavigationEventArgs e) { foreach (Contact item in context.Contacts) { Master.Items.Add(item.Name); } this.messageWebSocket = new MessageWebSocket(); // In this example, we send/receive a string, so we need to set the MessageType to Utf8. this.messageWebSocket.Control.MessageType = SocketMessageType.Utf8; this.messageWebSocket.MessageReceived += WebSocket_MessageReceived; this.messageWebSocket.Closed += WebSocket_Closed; try { connectTask = this.messageWebSocket.ConnectAsync(new Uri("wss://echo.websocket.org")).AsTask(); } catch (Exception ex) { WebErrorStatus webErrorStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add additional code here to handle exceptions. } }
private static async Task<string> GetUrl(string urlName) { if (urlName.ToLower().Equals("elvui")) { return ELVUI; } var uri = new Uri(@"https://www.curseforge.com/wow/addons/" + urlName); //using (var httpClient = new HttpClient()) //{ try { var response = await Http.WebHttpClient.GetStringAsync(uri); int index1 = response.IndexOf("<p class=\"infobox__cta\""); int index2 = response.Substring(index1).IndexOf("</p>"); string data = response.Substring(index1, index2); return Util.Parse2(data, "<a href=\"", "\">"); } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); if (error == Windows.Web.WebErrorStatus.Unknown) { Debug.WriteLine("[ERROR] FindProjectUrlFor " + uri + " " + ex.Message); } else { Debug.WriteLine("[ERROR] FindProjectUrlFor " + uri + " " + error); } } //} return string.Empty; }
public async Task <byte[]> ReceiveMessageFromWebSocketClientAsync(object webSocketClient, byte[] buffer, CancellationToken token) { var websocket = webSocketClient as StreamWebSocket; if (websocket == null) { throw new InvalidCastException("cannot cast webSocketClient object to StreamWebSocket"); } try { Stream readStream = websocket.InputStream.AsStreamForRead(); //await readStream.ReadAsync(buffer.AsBuffer(), Convert.ToUInt16(buffer.Length), InputStreamOptions.Partial); while (true) { int bytesReceived = 0; Debug.WriteLine("local address: " + websocket.Information.LocalAddress); int read = await readStream.ReadAsync(buffer, 0, buffer.Length, token); bytesReceived += read; bytesReceived -= 4; if (read < 4) { continue; // TODO: potential problem? } var lengthByte = new byte[4]; Array.Copy(buffer, lengthByte, 4); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthByte); } var length = BitConverter.ToInt32(lengthByte, 0); if (length == 0) { continue; // TODO: empty message? } byte[] incomingData = new byte[length]; Array.Copy(buffer, 4, incomingData, 0, read - 4); int index = read - 4; var rest = length - (read - 4); while (rest > 0) { read = await readStream.ReadAsync(buffer, 0, buffer.Length); bytesReceived += read; rest -= read; Array.Copy(buffer, 0, incomingData, index, read); index += read; } return(incomingData); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("Exception during message sending: " + ex.Message); throw; } }
public static string BuildWebSocketError(Exception ex) { ex = ex.GetBaseException(); if ((uint)ex.HResult == 0x800C000EU) { // INET_E_SECURITY_PROBLEM - our custom certificate validator rejected the request. return("Error: Rejected by custom certificate validation."); } WebErrorStatus status = WebSocketError.GetStatus(ex.HResult); // Normally we'd use the HResult and status to test for specific conditions we want to handle. // In this sample, we'll just output them for demonstration purposes. switch (status) { case WebErrorStatus.CannotConnect: case WebErrorStatus.NotFound: case WebErrorStatus.RequestTimeout: return("Cannot connect to the server. Please make sure " + "to run the server setup script before running the sample."); case WebErrorStatus.Unknown: return("COM error: " + ex.HResult); default: return("Error: " + status); } }
/// <summary> /// Raw websocket messages from server - convert to message types and call subscribers of events and/or callbacks /// </summary> /// <param name="sender"></param> /// <param name="args"></param> void mws_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { string read = null; try { using (DataReader reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; read = reader.ReadString(reader.UnconsumedBufferLength); Debug.WriteLine("[SOCKET_IO]: < " + read); } IMessage iMsg = SocketIOClient.Messages.Message.Factory(read); if (iMsg.Event == "responseMsg") { Debug.WriteLine(string.Format("InvokeOnEvent: {0}", iMsg.RawMessage)); } switch (iMsg.MessageType) { case SocketIOMessageTypes.Disconnect: this.OnMessageEvent(iMsg); if (string.IsNullOrWhiteSpace(iMsg.Endpoint)) // Disconnect the whole socket { this.Close(); } break; case SocketIOMessageTypes.Heartbeat: this.OnHeartBeatTimerCallback(null); break; case SocketIOMessageTypes.Connect: case SocketIOMessageTypes.Message: case SocketIOMessageTypes.JSONMessage: case SocketIOMessageTypes.Event: case SocketIOMessageTypes.Error: this.OnMessageEvent(iMsg); break; case SocketIOMessageTypes.ACK: this.registrationManager.InvokeCallBack(iMsg.AckId, iMsg.Json); break; default: Debug.WriteLine("unknown mws message Received..."); break; } } catch (Exception ex) // For debugging { this.mwsState = WebSocketState.Closed; WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("mws_MessageReceived::exception : " + status); this.OnErrorEvent(this, new ErrorEventArgs(status.ToString(), ex)); //this.Close(); } }
private async void button_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Debug.WriteLine("Starting... "); bool connecting = true; if (String.IsNullOrEmpty(playerName.Text)) { System.Diagnostics.Debug.WriteLine("Speler naam is niet aangegeven!"); return; } try { if (messageWebSocket == null) //Connection is not there yet.. lets make the bloody connection! { Uri server; if (!TryGetUri("ws://192.168.178.105:4141", out server)) { return; } //Server is now build.. messageWebSocket = new MessageWebSocket(); messageWebSocket.Control.MessageType = SocketMessageType.Utf8; messageWebSocket.MessageReceived += MessageReceived; // Dispatch close event on UI thread. This allows us to avoid synchronizing access to messageWebSocket. messageWebSocket.Closed += async(senderSocket, args) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Closed(senderSocket, args)); }; await messageWebSocket.ConnectAsync(server); messageWriter = new DataWriter(messageWebSocket.OutputStream); messageWriter.WriteString(playerName.Text); await messageWriter.StoreAsync(); } else if (messageWriter != null) { messageWriter.WriteString(playerName.Text); await messageWriter.StoreAsync(); } } catch (Exception er) { if (connecting && messageWebSocket != null) { messageWebSocket.Dispose(); messageWebSocket = null; } WebErrorStatus status = WebSocketError.GetStatus(er.GetBaseException().HResult); } }
// Continuously write outgoing data. For writing data we'll show how to use data.AsBuffer() to get an // IBuffer for use with webSocket.OutputStream.WriteAsync. Alternatively you can call // webSocket.OutputStream.AsStreamForWrite() to use .NET streams. private async void Scenario2SendData(object state) { int dataSent = 0; byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; MarshalText(OutputField, "Background sending data in " + data.Length + " byte chunks each second.\r\n"); try { IOutputStream writeStream = (IOutputStream)state; // Send until the socket gets closed/stopped while (true) { // using System.Runtime.InteropServices.WindowsRuntime; await writeStream.WriteAsync(data.AsBuffer()); dataSent += data.Length; MarshalText(DataSentField, dataSent.ToString(), false); // Delay so the user can watch what's going on. await Task.Delay(TimeSpan.FromSeconds(1)); } } catch (ObjectDisposedException) { MarshalText(OutputField, "Background write stopped.\r\n"); } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.OperationCanceled: MarshalText(OutputField, "Background write canceled.\r\n"); break; case WebErrorStatus.Unknown: throw; default: MarshalText(OutputField, "Error: " + status + "\r\n"); MarshalText(OutputField, ex.Message + "\r\n"); break; } } }
private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { using (DataReader reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string read = reader.ReadString(reader.UnconsumedBufferLength); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); } }
// stop it! private void End_OnClick(object sender, RoutedEventArgs e) { try { if (this.streamSocket != null) { streamSocket.Close(1000, "Closed per user request."); this.CloseStream(); } } catch (Exception ex) { var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); this.Primes.Text = string.Format("{0}: {1}", ex.Message, status); } }
/// <summary> /// When a message is received /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void WebSocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { using (DataReader dataReader = args.GetDataReader()) { dataReader.UnicodeEncoding = UnicodeEncoding.Utf8; message = dataReader.ReadString(dataReader.UnconsumedBufferLength); //this.messageWebSocket.Dispose(); } } catch (Exception ex) { WebErrorStatus webErrorStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add additional code here to handle exceptions. } }
// Continuously read incoming data. For reading data we'll show how to use activeSocket.InputStream.AsStream() // to get a .NET stream. Alternatively you could call readBuffer.AsBuffer() to use IBuffer with // activeSocket.InputStream.ReadAsync. private async Task ReceiveDataAsync(StreamWebSocket activeSocket) { Stream readStream = streamWebSocket.InputStream.AsStreamForRead(); int bytesReceived = 0; try { AppendOutputLine("Background read starting."); byte[] readBuffer = new byte[1000]; while (true) { if (streamWebSocket != activeSocket) { // Our socket is no longer active. Stop reading. AppendOutputLine("Background read stopped."); return; } int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Do something with the data. // This sample merely reports that the data was received. bytesReceived += read; DataReceivedField.Text = bytesReceived.ToString(); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.OperationCanceled: AppendOutputLine("Background read canceled."); break; default: AppendOutputLine("Error: " + status); AppendOutputLine(ex.Message); break; } } }
// Continuously write outgoing data. For writing data we'll show how to use data.AsBuffer() to get an // IBuffer for use with activeSocket.OutputStream.WriteAsync. Alternatively you can call // activeSocket.OutputStream.AsStreamForWrite() to use .NET streams. private async Task SendDataAsync(StreamWebSocket activeSocket) { int bytesSent = 0; byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; AppendOutputLine($"Background sending data in {data.Length} byte chunks each second."); try { // Send until the socket gets closed/stopped while (true) { if (streamWebSocket != activeSocket) { // Our socket is no longer active. Stop sending. AppendOutputLine("Background write stopped."); return; } await activeSocket.OutputStream.WriteAsync(data.AsBuffer()); bytesSent += data.Length; DataSentField.Text = bytesSent.ToString(); // Delay so the user can watch what's going on. await Task.Delay(TimeSpan.FromSeconds(1)); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.OperationCanceled: AppendOutputLine("Background write canceled."); break; default: AppendOutputLine("Error: " + status); AppendOutputLine(ex.Message); break; } } }
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); } }
private void Connection_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { using (var dr = args.GetDataReader()) { dr.UnicodeEncoding = UnicodeEncoding.Utf8; var message = dr.ReadString(dr.UnconsumedBufferLength); var obj = JsonConvert.DeserializeObject <dynamic>(message); var id = (string)obj.id; var type = (string)obj.type; TaskCompletionSource <dynamic> taskCompletion; if (type == "registered") { if (_tokens.TryRemove(id, out taskCompletion)) { var key = (string)JObject.Parse(message)["payload"]["client-key"]; taskCompletion.TrySetResult(new { clientKey = key }); } } else if (_tokens.TryGetValue(id, out taskCompletion)) { if (id == "register_0") { return; } if (obj.type == "error") { taskCompletion.SetException(new Exception(obj.error)); } //else if (args.Cancelled) //{ // taskSource.SetCanceled(); //} taskCompletion.TrySetResult(obj.payload); } } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); } }
private async void ReceiveData(object state) { int bytesReceived = 0; try { Stream readStream = (Stream)state; while (true) // Until closed and ReadAsync fails. { int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length); bytesReceived += read; StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(readBuffer, 0, readBuffer.Length)); string[] o = sb.ToString().Split(' '); // 打断字符串 TimeSpan k = new TimeSpan(); k = (TimeSpan)(DateTime.UtcNow - startDT); // 得到开始到现在所消耗的时间 CurrentUTCTime = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-k); // 减去中途消耗的时间 if (_callback != null) { _callback(CurrentUTCTime); } } } catch (ObjectDisposedException) { CurrentHostIndex++; if (CurrentHostIndex < whost.Length) { ConnectInternetTime(); } else { _callback(null); } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add your specific error-handling code here. } }