public async Task<bool> Connect(Uri uri, bool ignoreReceiver = false) { try { _commandCount = 0; _connection = new MessageWebSocket(); _connection.Control.MessageType = SocketMessageType.Utf8; // if(ignoreReceiver==false) _connection.MessageReceived += Connection_MessageReceived; _connection.Closed += Connection_Closed; await _connection.ConnectAsync(uri); IsConnected?.Invoke(true); _messageWriter = new DataWriter(_connection.OutputStream); return true; } catch (Exception e) { switch (SocketError.GetStatus(e.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error break; default: // Handle Unknown Error break; } return false; } }
public async Task Connect() { if (!_isLoggedIn) throw new DiscordException(ExceptionList.NotLoggedIn); _socket = new MessageWebSocket(); _writer = new DataWriter(_socket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8 }; _socket.Control.MessageType = SocketMessageType.Utf8; _socket.MessageReceived += socket_MessageReceived; string gatewayUrl = await GetGateway(); await _socket.ConnectAsync(new Uri(gatewayUrl)); JsonObject request = new JsonObject { { "op", JsonValue.CreateNumberValue(2) }, { "d", new JsonObject { { "token", JsonValue.CreateStringValue(_token) }, { "v", JsonValue.CreateNumberValue(3) }, { "properties", new JsonObject { { "$os", JsonValue.CreateStringValue("Windows") } }}, { "large_threshold", JsonValue.CreateNumberValue(0) } } } }; await WriteToSocket(request.Stringify()); }
// WebSockets Button private async void Button_Click(object sender, RoutedEventArgs e) { try { //creates a new MessageWebSocket and connects to WebSocket server and sends data to server //Make a local copy MessageWebSocket webSocket = messageWebSocket; //Have we connected yet? if (webSocket == null) { Uri server = new Uri(ServerAddressField.Text.Trim()); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; messageWriter = new DataWriter(webSocket.OutputStream); } //InputField is a textbox in the xaml string message = InputField.Text; messageWriter.WriteString(message); await messageWriter.StoreAsync(); } catch (Exception ex) { String.Format("There is an error in connection"); } }
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { if (args.ShareOperation.Data.Contains(StandardDataFormats.WebLink)) { Uri uri = await args.ShareOperation.Data.GetWebLinkAsync(); if (null != uri) try { using (var socket = new MessageWebSocket()) { socket.Control.MessageType = SocketMessageType.Utf8; await socket.ConnectAsync(new Uri("ws://" + settings["Host"].ToString() + ":" + settings["Port"].ToString())); using (var writer = new DataWriter(socket.OutputStream)) { writer.WriteString(uri.AbsoluteUri); await writer.StoreAsync(); args.ShareOperation.ReportCompleted(); } } } catch { show(); } } }
public IEnumerator Connect() { #endif #if !UNITY_EDITOR m_Socket = new Windows.Networking.Sockets.MessageWebSocket(); // In this example, we send/receive a string, so we need to set the MessageType to Utf8. m_Socket.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8; m_Socket.MessageReceived += WebSocket_MessageReceived; m_Socket.Closed += WebSocket_Closed; try { Task connectTask = m_Socket.ConnectAsync(new Uri(mUrl.ToString())).AsTask(); // connectTask.ContinueWith(_ => this.SendMessageUsingMessageWebSocketAsync("Hello, World!")); } catch (Exception ex) { Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add additional code here to handle exceptions. FlowNetworkManager.log(ex.Message); } yield return 0; }
public void Open(string url) { receiveQueue.Clear(); Dispose(); try { socket = new MessageWebSocket(); socket.Control.MessageType = SocketMessageType.Binary; socket.MessageReceived += (s, e) => { try { using (var reader = e.GetDataReader()) { var buf = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(buf); if (e.MessageType == SocketMessageType.Binary) { Debug.WriteLine("WebSocket MessageReceived(binary): length=" + buf.Length); lock (syncRoot) { receiveQueue.Enqueue(buf); } } else { Debug.WriteLine("WebSocket MessageReceived(text): " + Encoding.UTF8.GetString(buf, 0, buf.Length)); } } } catch (Exception ex) { Connected = false; var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("WebSocket MessageReceived Error: " + status); } }; socket.Closed += (s, e) => Debug.WriteLine("WebSocket Closed"); socket.ConnectAsync(new Uri(url)).AsTask().Wait(); Connected = true; Debug.WriteLine("WebSocket Opened"); writer = new DataWriter(socket.OutputStream); } catch (Exception ex) { Connected = false; var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("WebSocket Open Error: " + status); } }
public async Task<bool> SetupWebSocket() { bool worked = false; try { ServerListItem server = settings.GetServer(); if (server == null) { return false; //throw new Exception("Server not set"); } Uri serverUri = new Uri("ws://" + server + "/mediabrowser"); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(serverUri); DataWriter messageWriter = new DataWriter(webSocket.OutputStream); string deviceName = settings.GetDeviceName(); string value = "SPMB"; if (string.IsNullOrEmpty(deviceName) == false) { value = "SPMB-" + settings.GetDeviceName(); } string identityMessage = "{\"MessageType\":\"Identity\", \"Data\":\"Windows RT|" + settings.GetDeviceId() + "|0.0.1|" + value + "\"}"; messageWriter.WriteString(identityMessage); await messageWriter.StoreAsync(); worked = true; } catch(Exception e) { MetroEventSource.Log.Info("Error Creating WebSocket - " + e.Message); string errorString = "Error Creating WebSocket : " + e.Message; App.AddNotification(new Notification() { Title = "Error Creating Web Socket", Message = errorString }); } return worked; }
public async void 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); //Connected(this, EventArgs.Empty); keepAliveTimer = new Timer(sendKeepAlive, null, TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS), TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS)); messageWriter = new DataWriter(socket.OutputStream); } 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; } } Debug.WriteLine("WSC connected..."); } }
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); } }
public void connect() { dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { try { state = WebSocketState.CONNECTING; //[email protected]("Connecting to " + url); await sck.ConnectAsync(new Uri(url)); state = WebSocketState.OPEN; messageWriter = new DataWriter(sck.OutputStream); com.codename1.io.websocket.WebSocket.openReceived(id); } catch (Exception ex) { state = WebSocketState.CLOSED; com.codename1.io.websocket.WebSocket.errorReceived(id, ex.Message, ex.HResult); } }).AsTask().GetAwaiter().GetResult(); }
async void SensorValueChanged(object sender, X2CodingLab.SensorTag.SensorValueChangedEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { switch (e.Origin) { case SensorName.Accelerometer: // WebSockets MessageWebSocket webSocket = messageWebSocket; if (webSocket == null) { Uri server = new Uri("ws://localhost:8181"); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; messageWriter = new DataWriter(webSocket.OutputStream); } string message = null; //byte[] accValue = await acc.ReadValue(); double[] accAxis = Accelerometer.CalculateCoordinates(e.RawData, 1 / 64.0); double xRaw = accAxis[0] / 4; double yRaw = accAxis[1] / 4; message = "SET RAW_INPUT " + xRaw.ToString("0.00000") + "," + yRaw.ToString("0.00000"); info.Text = message; messageWriter.WriteString(message); await messageWriter.StoreAsync(); break; } }); }
private async Task ConnectAsync() { if (String.IsNullOrEmpty(InputField.Text)) { rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage); return; } // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not // valid WebSocket URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet // or intErnet. In these cases the app requires the "Home or Work Networking" or // "Internet (Client)" capability respectively. Uri server = rootPage.TryGetUri(ServerAddressField.Text); if (server == null) { return; } messageWebSocket = new MessageWebSocket(); messageWebSocket.Control.MessageType = SocketMessageType.Utf8; messageWebSocket.MessageReceived += MessageReceived; messageWebSocket.Closed += OnClosed; // If we are connecting to wss:// endpoint, by default, the OS performs validation of // the server certificate based on well-known trusted CAs. We can perform additional custom // validation if needed. if (SecureWebSocketCheckBox.IsChecked == true) { // WARNING: Only test applications should ignore SSL errors. // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle // attacks. (Although the connection is secure, the server is not authenticated.) // Note that not all certificate validation errors can be ignored. // In this case, we are ignoring these errors since the certificate assigned to the localhost // URI is self-signed and has subject name = fabrikam.com messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing // custom validation of the server certificate. The event handler must implement the desired // custom certificate validation logic. messageWebSocket.ServerCustomValidationRequested += OnServerCustomValidationRequested; // Certificate validation occurs only for secure connections. if (server.Scheme != "wss") { AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme."); } } AppendOutputLine($"Connecting to {server}..."); try { await messageWebSocket.ConnectAsync(server); } catch (Exception ex) // For debugging { // Error happened during connect operation. messageWebSocket.Dispose(); messageWebSocket = null; AppendOutputLine(MainPage.BuildWebSocketError(ex)); AppendOutputLine(ex.Message); return; } // The default DataWriter encoding is Utf8. messageWriter = new DataWriter(messageWebSocket.OutputStream); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); }
private async Task ConnectToWebSocket() { // first clean up any potential existing sockets or whatever since we might be reconnecting // due to a server migration Cleanup(); Uri startUrl = new Uri("https://slack.com/api/rtm.start?token=" + accessToken); DateTime initialConnectionTime = DateTime.UtcNow; bool connected = false; JObject responseObject = null; do { responseObject = await GetWebData(startUrl); if ((bool)responseObject["ok"]) { connected = true; break; } else { // if there was an error connecting wait 2 seconds await Task.Delay(TimeSpan.FromSeconds(2)); } } // only try to connect for 30 seconds since thats how long the WebSocket url lasts while (DateTime.UtcNow - initialConnectionTime < TimeSpan.FromSeconds(30)); if (!connected) { WriteToOutputBox("Something happened while trying to connect (we couldn't connect)"); return; } string socketUrl = (string)responseObject["url"]; // find the general channel, that's where we want to look for messages foreach (JObject channel in responseObject["channels"]) { if ((bool)channel["is_general"]) { generalChannelId = (string)channel["id"]; } } // load in the slack users foreach (JObject user in responseObject["users"]) { users.Add(new SlackUser((string)user["id"], (string)user["name"], (string)user["profile"]["first_name"], (string)user["profile"]["last_name"], (string)user["profile"]["real_name"])); } // setup and connect to the websocket webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += WebSocket_MessageReceived; await webSocket.ConnectAsync(new Uri(socketUrl)); // we also set up a writer so we can write to the websocket even though we currently don't use it // potential writer = new StreamWriter(webSocket.OutputStream.AsStreamForWrite(), System.Text.Encoding.UTF8); }
private async void Start_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(InputField.Text)) { rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage); return; } bool connecting = true; try { // Have we connected yet? if (messageWebSocket == null) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not // valid WebSocket URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet // or intErnet. In these cases the app requires the "Home or Work Networking" or // "Internet (Client)" capability respectively. Uri server; if (!rootPage.TryGetUri(ServerAddressField.Text, out server)) { return; } rootPage.NotifyUser("Connecting to: " + server, NotifyType.StatusMessage); 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); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Already connected", NotifyType.StatusMessage); } connecting = false; string message = InputField.Text; OutputField.Text += "Sending Message:\r\n" + message + "\r\n"; // Buffer any data we want to send. messageWriter.WriteString(message); // Send the data as one complete message. await messageWriter.StoreAsync(); rootPage.NotifyUser("Send Complete", NotifyType.StatusMessage); } catch (Exception ex) // For debugging { // Error happened during connect operation. if (connecting && messageWebSocket != null) { messageWebSocket.Dispose(); messageWebSocket = null; } WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.CannotConnect: case WebErrorStatus.NotFound: case WebErrorStatus.RequestTimeout: rootPage.NotifyUser("Cannot connect to the server. Please make sure " + "to run the server setup script before running the sample.", NotifyType.ErrorMessage); break; case WebErrorStatus.Unknown: throw; default: rootPage.NotifyUser("Error: " + status, NotifyType.ErrorMessage); break; } OutputField.Text += ex.Message + "\r\n"; } }
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); }
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); } }
public async void Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled += OnCanceled; _deferral = taskInstance.GetDeferral(); _taskInstance = taskInstance; //var messageReceiver = new TextSecureMessageReceiver(PUSH_URL, TextSecurePreferences.getLocalNumber(), TextSecurePreferences.getPushServerPassword(), TextSecurePreferences.getSignalingKey(), "Test User Agent"); //var connection = new WebSocketConnection(PUSH_URL, TextSecurePreferences.getLocalNumber(), TextSecurePreferences.getPushServerPassword(), "Test User Agent"); //connection.Connected += OnConnected; var username = TextSecurePreferences.getLocalNumber(); var password = TextSecurePreferences.getPushServerPassword(); var userAgent = "ASdfA"; try { socket = new MessageWebSocket(); if (userAgent != null) socket.SetRequestHeader("X-Signal-Agent", userAgent); socket.MessageReceived += OnMessageReceived; socket.Closed += OnClosed; var wsUri = PUSH_URL.Replace("https://", "wss://") .Replace("http://", "ws://") + $"/v1/websocket/?login={username}&password={password}"; Uri server = new Uri(wsUri); await socket.ConnectAsync(server); Debug.WriteLine("WebsocketTask connected..."); keepAliveTimer = new Timer(sendDisconnect, null, TimeSpan.FromSeconds(15), Timeout.InfiniteTimeSpan); //messageWriter = new DataWriter(socket.OutputStream); } 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; } Debug.WriteLine("fuuuu"); socket.Close(1000, "None"); } //var pipe = messageReceiver.createMessagePipe(); // pipe.MessageReceived += OnMessageRecevied; }
private async void InitializeInBackground(int id, string url, MessageWebSocket webSocket) { try { await webSocket.ConnectAsync(new Uri(url)).AsTask().ConfigureAwait(false); _webSocketConnections.Add(id, webSocket); var dataWriter = new DataWriter(webSocket.OutputStream); dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8; _dataWriters.Add(id, dataWriter); SendEvent("websocketOpen", new JObject { { "id", id }, }); } catch (Exception ex) { OnError(id, ex); } }
private async void connectButton_Click(object sender, RoutedEventArgs e) { Uri uri; if (mws == null) { NotifyUser("Starting to connect", NotifyType.StatusMessage); // validate the URI if (TryGetUri(this.urlBox.Text, out uri)) { try { NotifyUser("URI is good. Connecting.", NotifyType.StatusMessage); mws = new MessageWebSocket(); // sending UTF8 as Binary will make our target web service wait 30 seconds before echoing. mws.Control.MessageType = SocketMessageType.Binary; // add a mws.MessageRecieved handler here, to receive data from the connected remote endpoint mws.MessageReceived += Mws_MessageReceived; // add a mws.Closed hander here, to properly maintain state when the other end closes the connection // Dispatch close event on UI thread. This allows us to avoid synchronizing access to messageWebSocket. mws.Closed += async (senderSocket, args) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Mws_Closed(senderSocket, args)); }; // connect on the websocket await mws.ConnectAsync(uri); NotifyUser("Connected.", NotifyType.StatusMessage); connectButton.Content = "Disconnect"; messageWriter = new DataWriter(mws.OutputStream); } catch (Exception ex) { string msg = ex.Message; NotifyUser("Error connecting: " + msg, NotifyType.ErrorMessage); } } else { NotifyUser("Invalid URI", NotifyType.ErrorMessage); } } else { NotifyUser("Disconnecting.", NotifyType.StatusMessage); // disconnecting try { mws.Close(1000, "opening new one"); mws = null; NotifyUser("Disconnected", NotifyType.StatusMessage); connectButton.Content = "Connect"; } catch (Exception ex) { string msg = ex.Message; NotifyUser("Error disconnecting: " + msg, NotifyType.ErrorMessage); } } }
/// <summary> /// Initiate the connection with Socket.IO service /// </summary> public async void ConnectAsync() { if (!(this.ReadyState == WebSocketState.Connecting || this.ReadyState == WebSocketState.Connected)) { try { this.ConnectionOpenEvent.Reset(); this.HandShake = await this.requestHandshake(uri);// perform an initial HTTP request as a new, non-handshaken connection if (this.HandShake == null || string.IsNullOrWhiteSpace(this.HandShake.SID) || this.HandShake.HadError) { Debug.WriteLine("Error initializing handshake with {0}", uri.ToString()); } else { string wsScheme = (uri.Scheme == "https" ? "wss" : "ws"); this.mws = new MessageWebSocket(); mws.Control.MessageType = SocketMessageType.Utf8; this.mws.MessageReceived += mws_MessageReceived; this.mws.Closed += mws_Closed; this.mwsState = WebSocketState.Connecting; Debug.WriteLine("ConnectAsync : Connecting on : "+string.Format("{0}://{1}:{2}/socket.io/1/websocket/{3}", wsScheme, uri.Host, uri.Port, this.HandShake.SID)); await mws.ConnectAsync(new Uri(string.Format("{0}://{1}:{2}/socket.io/1/websocket/{3}", wsScheme, uri.Host, uri.Port, this.HandShake.SID))); this.mwsState = WebSocketState.Connected; mws_OpenEvent(); Debug.WriteLine("mws_Opened : websocket opened !"); } } catch (Exception ex) { this.mwsState = WebSocketState.Closed; Debug.WriteLine(string.Format("Connect threw an exception...{0}", ex.GetBaseException().HResult)); WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); this.OnErrorEvent(this, new ErrorEventArgs(status.ToString(), ex)); } } }
public async void Connect(string url) { if (pending != null) { pending.Dispose(); } Uri uri; var connectionId = Strings.RandomString(8); var serverId = Strings.RandomNumber(1, 1000); try { uri = new Uri(url); } catch (Exception) { throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url)); } try { var prefix = "https".Equals(uri.Scheme) ? "wss" : "ws"; var connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId)); pending = new MessageWebSocket(); pending.Control.MessageType = SocketMessageType.Utf8; pending.Closed += Closed; pending.MessageReceived += MessageReceived; try { await pending.ConnectAsync(connectionUrl); } catch(Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.CannotConnect: throw new Exception("Can't connect" + ex.Message); case WebErrorStatus.NotFound: throw new Exception("Not found" + ex.Message); case WebErrorStatus.RequestTimeout: throw new Exception("Request timeout" + ex.Message); default: throw new Exception("unknown" + ex.Message); } } streamWebSocket = pending; messageWriter = new DataWriter(pending.OutputStream); var ev = _onOpened; if (ev != null) { ev(); } } catch { throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url)); } }
private async Task ConnectAsync() { if (String.IsNullOrEmpty(InputField.Text)) { rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage); return; } // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not // valid WebSocket URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet // or intErnet. In these cases the app requires the "Home or Work Networking" or // "Internet (Client)" capability respectively. Uri server = rootPage.TryGetUri(ServerAddressField.Text); if (server == null) { return; } messageWebSocket = new MessageWebSocket(); messageWebSocket.Control.MessageType = SocketMessageType.Utf8; messageWebSocket.MessageReceived += MessageReceived; messageWebSocket.Closed += OnClosed; AppendOutputLine($"Connecting to {server}..."); try { await messageWebSocket.ConnectAsync(server); } catch (Exception ex) // For debugging { // Error happened during connect operation. messageWebSocket.Dispose(); messageWebSocket = null; AppendOutputLine(MainPage.BuildWebSocketError(ex)); AppendOutputLine(ex.Message); return; } // The default DataWriter encoding is Utf8. messageWriter = new DataWriter(messageWebSocket.OutputStream); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); }
private async void WebSocket() { try { Uri uri = new Uri("ws://169.254.195.254:1337"); HttpClient client = new HttpClient(); //var tot = new Windows.Networking.Sockets.StreamWebSocket(); //await tot.ConnectAsync(uri); var result = await client.PostAsync("http://169.254.195.254:1337/app/connectedobjects/ringring", new System.Net.Http.StringContent(@"{ ""tokenObject"": ""fefedeizzef84zfse8fz"" }")); MessageWebSocket message = new MessageWebSocket(); message.Closed += Message_Closed; message.MessageReceived += Message_MessageReceived; await message.ConnectAsync(uri); //await message.ConnectAsync(new Uri("ws://169.254.195.254:1337/connectedobjects/fefedeizzef84zfse8fz/connectedObjectSubscribe")); } catch (Exception) { } }
internal async void ConnectChatServer(string serverUrl) { //this.webSocketClient = new WebSocket(serverUrl, "", (List<KeyValuePair<string, string>>) null, // (List<KeyValuePair<string, string>>) null, "", "", (WebSocketVersion) - 1); webSocketClient=new MessageWebSocket(); await webSocketClient.ConnectAsync(new Uri(serverUrl)); this.connected = true; //this.webSocketClient.add_Opened(new EventHandler(this.webSocketClient_Opened)); //this.webSocketClient.add_DataReceived( // new EventHandler<DataReceivedEventArgs>(this.webSocketClient_DataReceived)); this.webSocketClient.Closed+=WebSocketClient_Closed; this.webSocketClient.MessageReceived+=this.webSocketClient_MessageReceived; //this.webSocketClient.add_Error(new EventHandler<ErrorEventArgs>(this.webSocketClient_Error)); //this.webSocketClient.Open(); }
internal Task<bool> InitializeAsync() { string serverUrl = string.Format(this.RTC_Router_Server, (object) AVClient.ApplicationId); return InternalExtensions.OnSuccess( AVClient.platformHooks.RequestAsync(new Uri(serverUrl), "GET", null, null, string.Empty, CancellationToken.None), t => { serverUrl = AVClient.DeserializeJsonString(t.Result.Item2)["server"].ToString(); webSocketClient = new MessageWebSocket(); webSocketClient.ConnectAsync(new Uri(serverUrl)).GetResults(); webSocketClient.Closed += WebSocketClient_Closed; //this.webSocketClient = new WebSocket(serverUrl, "", null, null, "", "", (WebSocketVersion) - 1); //this.webSocketClient.Open(); //this.webSocketClient.add_Closed(new EventHandler(this.webSocketClient_Closed)); TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); //EventHandler callback = (EventHandler)null; //callback = (EventHandler)((s, e) => //{ // tcs.TrySetResult(true); // this.status = SocketStatus.SocketConnected; // this.webSocketClient.remove_Opened(callback); //}); //this.webSocketClient.add_Opened(callback); tcs.TrySetResult(true); return tcs.Task.Result; }); }
private async Task OpenWebSocketAsync() { _closeTaskCompletionSource = new TaskCompletionSource<object>(); try { var webSocketUrl = (await GetApiInfoAsync()).WebSocketServerUrl + "/client"; _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.MessageReceived += (s, e) => Task.Run(() => HandleMessage(e)); _webSocket.Closed += (s, e) => Task.Run(() => HandleConnectionClose()); await _webSocket.ConnectAsync(new Uri(webSocketUrl)); _socketWriter = new DataWriter(_webSocket.OutputStream); await AuthenticateAsync(); SetChannelState(ChannelState.Connected); } catch { try { if (_webSocket != null) { _webSocket.Close(1000, "Abnormal Closure"); } } catch { } finally { if (_webSocket != null) { _webSocket.Dispose(); _webSocket = null; } SetChannelState(ChannelState.Disconnected); } throw; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // retrieve the username from the payload _username = (string)e.Parameter; try { // Make a local copy to avoid races with Closed events. MessageWebSocket webSocket = messageWebSocket; // Have we connected yet? if (webSocket == null) { Uri server = new Uri("ws://vdev-pc/svc/SocketChatService.svc"); webSocket = new MessageWebSocket(); // 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; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; // Only store it after successfully connecting. messageWriter = new DataWriter(webSocket.OutputStream); } // create the main message and serialize to string SocketServiceMessage msgBody = new SocketServiceMessage() { Action = SocketServiceAction.Login, Username = _username }; string msgBodyString = JsonConvert.SerializeObject(msgBody); // Buffer any data we want to send. messageWriter.WriteString(msgBodyString); // Send the data as one complete message. await messageWriter.StoreAsync(); } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); } }