public static async Task RestartSocket() { socket = new MessageWebSocket(); socket.MessageReceived += MessageWebSocket_MessageReceived; socket.Closed += MessageWebSocket_Closed; socket.Control.MessageType = SocketMessageType.Binary; try { if (App.isRPi) { await socket.ConnectAsync(new Uri($"ws://{App.ServiceUri}/camera/sender/?device=camera")); } else { await socket.ConnectAsync(new Uri($"ws://{App.ServiceUri}/camera/receiver/?device=camera")); } socketIsConnected = true; Debug.WriteLine("Camera web socket restarted!"); } catch (Exception ex) { socket.Dispose(); socket = null; socketIsConnected = false; Debug.WriteLine("Error restarting camera web socket: " + ex.Message); } }
private static async Task OpenSocket() { if (socket != null) { CloseSocket(); } try { if (App.isRPi) { await socket.ConnectAsync(new Uri($"ws://{App.ServiceUri}/camera/sender/?device=camera")); } else { await socket.ConnectAsync(new Uri($"ws://{App.ServiceUri}/camera/receiver/?device=camera")); } socketIsConnected = true; Debug.WriteLine("Camera web socket connected!"); } catch (Exception ex) { socket.Dispose(); socket = null; socketIsConnected = false; Debug.WriteLine("Error connecting to camera web socket: " + ex.Message); } }
public IEnumerator Connect() { m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData); m_Socket.OnOpen += (sender, e) => { if (OnOpen != null) { OnOpen.Invoke(sender, e); } m_IsConnected = true; }; m_Socket.OnClose += (sender, e) => { if (OnClose != null) { OnClose.Invoke(sender, e); } }; m_Socket.OnError += (sender, e) => m_Error = e.Message; m_Socket.ConnectAsync(); while (!m_IsConnected && m_Error == null) { yield return(0); } }
public async Task Initialize() { try { if (this.CurrentSocket == null) { CurrentResponse = string.Empty; this.CurrentSocket = new MessageWebSocket(); Uri server = new Uri("ws://echo.websocket.org"); // MessageWebSocket supports both utf8 and binary messages. // When utf8 is specified as the messageType, then the developer // promises to only send utf8-encoded data. CurrentSocket.Control.MessageType = SocketMessageType.Utf8; // Set up callbacks CurrentSocket.MessageReceived += MessageReceived; CurrentSocket.Closed += Closed; await CurrentSocket.ConnectAsync(server); } } catch (Exception ex) // For debugging { //WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add your specific error-handling code here. Util.HandleMessage("Some problem happened with setting up Chat server", ex.ToString(), "Sorry"); } }
public async void Connect() { Logger.Debug("Signaling", "Connect"); if (closed) { Logger.Debug("Signaling", "already closed"); return; } try { await socket.ConnectAsync(new Uri($"{endpoint}?channel_id={channelId}")); socketWriter = new DataWriter(socket.OutputStream); OnConnect?.Invoke(); await SendConnectMessage(); } catch (Exception ex) { Logger.Debug("Signaling", $"failed to connect websocket: {ex.Message}"); OnError?.Invoke(ErrorType.SocketCantConnect); } }
protected virtual async Task ExecuteConnectAsync() { var hasError = true; var isDisposed = true; while (hasError) { try { if (isDisposed) { currentSocket = new MessageWebSocket(); currentSocket.MessageReceived += SocketMessageReceived; currentSocket.Closed += SocketClosed; } await currentSocket.ConnectAsync(uri); hasError = false; } catch (Exception e) { isDisposed = e is ObjectDisposedException; await Task.Delay(Interval); } } Debug.WriteLine("Socket #\{currentSocket.GetHashCode()} created");
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 { } throw; } }
async void webSocketSetup() { //Setting up the websocket connection with the leap motion service //Debug.Log("Setting up websocket"); w = new MessageWebSocket(); //In this case we will be sending/receiving a string so we need to set the MessageType to Utf8. w.Control.MessageType = SocketMessageType.Utf8; //Add the MessageReceived event handler. w.MessageReceived += WebSock_MessageReceived; //Add the Closed event handler. w.Closed += WebSock_Closed; Uri serverUri = new Uri(WEBSOCKET_URI_REMOTE); try { //Connect to the server. await w.ConnectAsync(serverUri); //Send a message to the server. await WebSock_SendMessage(w, flag); await WebSock_SendMessage(w, GET_FOCUS); } catch (Exception ex) { //Add code here to handle any exceptions Debug.Log(ex.StackTrace); } }
public static async void SendMessage(string message) { try { string address = "192.168.1.1"; MessageWebSocket webSocket = Network.messageWebSocket; if (webSocket == null) { Uri server = new Uri(address); webSocket = new MessageWebSocket(); // callbacks webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; // connect await webSocket.ConnectAsync(server); Network.messageWebSocket = webSocket; Network.messageWriter = new DataWriter(webSocket.OutputStream); } messageWriter.WriteUInt32(messageWriter.MeasureString(message)); messageWriter.WriteString(message); await Network.messageWriter.StoreAsync(); } catch (Exception e) // For debugging { string error = e.Message; } }
/* Websockets begin */ 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"); } }
private async void ConnectToWebSocket() { webSocket = new MessageWebSocket(); webSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); webSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); webSocket.Control.MessageType = SocketMessageType.Utf8; if (!String.IsNullOrEmpty(PasswordResource) && !String.IsNullOrEmpty(WebBUsername) && !String.IsNullOrEmpty(WebBPassword)) { webSocket.Control.ServerCredential = new PasswordCredential(PasswordResource, WebBUsername, WebBPassword); } webSocket.MessageReceived += WebSocket_MessageReceived; webSocket.Closed += WebSocket_Closed; var uri = new Uri($"wss://localhost:{WebBPort}/api/etw/session/realtime"); try { await webSocket.ConnectAsync(uri); var enableMsg = "provider 9f7e92de-9bd1-5b43-9cbd-e332a6ed01e6 enable 5"; await SendWebSocketMessageAsync(enableMsg); StoreCredential(); } catch (Exception e) { webSocket = null; var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ConnectionErrorMsg = e.Message; }); } }
void initializeWebSocket() { if (wsURL != null) { #if WINDOWS_UWP ws = new MessageWebSocket(); ws.Control.MessageType = SocketMessageType.Utf8; #else ws = new WebSocket(wsURL); #endif } else { Debug.Log("Web Socket intialize failure."); return; } #if WINDOWS_UWP ws.MessageReceived += Websocket_MessageReceived; var task = Task.Run(async() => { await ws.ConnectAsync(new Uri(wsURL)); }); task.Wait(); #else ws.OnOpen += onOpen; ws.OnMessage += onMessage; ws.OnError += onError; ws.OnClose += onClose; ws.Connect(); #endif }
public static async Task InitialWebSocket() { ws = new MessageWebSocket(); ws.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8; ws.MessageReceived += WebSocket_ReceivedMessage; await ws.ConnectAsync(new Uri(wssPrefix + AccessingURI + wssPostfix)); }
public async Task <bool> Connect(Uri uri, bool ignoreReceiver = false) { try { ConnectionClosed = false; _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 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(); } }
private async Task <bool> ConnectedToWebSocket() { if (!_isConnected) { _webSock = new MessageWebSocket(); _webSock.Control.MessageType = SocketMessageType.Utf8; _webSock.MessageReceived += WebSock_MessageReceived; _webSock.Closed += WebSock_Closed; _messageWriter = new DataWriter(_webSock.OutputStream); try { await _webSock.ConnectAsync(_serverUri); _isConnected = true; } catch (Exception ex) { await _log.ErrorAsync("Fehler beim Herstellen der Verbindung zum Server.", ex); CloseWebSocketConnection(); _isConnected = false; } } return(_isConnected); }
public async Task StartAsync(string requestQuality = "", bool isLowLatency = true) { var broadcastId = Props.Program.BroadcastId; var audienceToken = Props.Player.AudienceToken; using (var releaser = await _WebSocketLock.LockAsync()) { Debug.WriteLine($"providerType: {Props.Program.ProviderType}"); Debug.WriteLine($"comment websocket url: {Props.Site.Relive.WebSocketUrl}"); await MessageWebSocket.ConnectAsync(new Uri(Props.Site.Relive.WebSocketUrl)); _DataWriter = new DataWriter(MessageWebSocket.OutputStream); } if (string.IsNullOrEmpty(requestQuality)) { requestQuality = "high"; } var getpermitCommandText = $@"{{""type"":""watch"",""body"":{{""command"":""getpermit"",""requirement"":{{""broadcastId"":""{broadcastId}"",""route"":"""",""stream"":{{""protocol"":""hls"",""requireNewStream"":true,""priorStreamQuality"":""{requestQuality}"", ""isLowLatency"":{isLowLatency.ToString().ToLower()}}},""room"":{{""isCommentable"":true,""protocol"":""webSocket""}}}}}}}}"; //var getpermitCommandText = $"{{\"type\":\"watch\",\"body\":{{\"params\":[\"{Props.BroadcastId}\",\"\",\"true\",\"hls\",\"\"],\"command\":\"getpermit\"}}}}"; await SendMessageAsync(getpermitCommandText); }
// connects with the ROSbridge server public async void Connect() { MaybeLog("Connect..."); //this.debugHUDText.text += "\n"; //this.debugHUDText.text += "Connecting..."; webSock = new MessageWebSocket(); webSock.Control.MessageType = SocketMessageType.Utf8; //Add the MessageReceived event handler. if (verbose) { this.debugHUDText.text = "\n Register Incoming Message Handler..." + this.debugHUDText.text; } webSock.MessageReceived += WebSock_MessageReceived; //Add the Closed event handler. webSock.Closed += WebSock_Closed; try { //Connect to the server. await webSock.ConnectAsync(serverUri); } catch (Exception ex) { this.debugHUDText.text = ex.Message; } }
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 async void Connect() { await ws.ConnectAsync(uri); writer = new DataWriter(ws.OutputStream); connected = true; }
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()); } } }
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 async Task ConnectToWebSocket() { var rnd = new Random().Next(40) + 50; string server = "ws://" + ws_server + ":80" + rnd; Uri serverConnect = new Uri(server); if (serverConnect == null) { return; } messageWebSocket = new MessageWebSocket(); messageWebSocket.Control.MessageType = SocketMessageType.Utf8; messageWebSocket.MessageReceived += MessageReceived; messageWebSocket.Closed += OnClosed; try { await messageWebSocket.ConnectAsync(serverConnect); } catch (Exception ex) // For debugging { // Error happened during connect operation. messageWebSocket.Dispose(); messageWebSocket = null; Debug.WriteLine(ex); return; } messageWriter = new DataWriter(messageWebSocket.OutputStream); await SendAsync(); }
public async void InitWebSockets() { MessageWebSocket webSock = new MessageWebSocket(); //In this case we will be sending/receiving a string so we need to set the MessageType to Utf8. webSock.Control.MessageType = SocketMessageType.Utf8; Debug.WriteLine("InitWebSockets - We made it!"); //await Task.Delay(2000); //Add the MessageReceived event handler. webSock.MessageReceived += WebSock_MessageReceived; //Add the Closed event handler. webSock.Closed += WebSock_Closed; Uri serverUri = new Uri("ws://echo.websocket.org"); /// Denne del er kun til test try { //Connect to the server. await webSock.ConnectAsync(serverUri); Debug.WriteLine("serverUri " + serverUri); //Send a message to the server. await WebSock_SendMessage(webSock, "<ArduinoCollection><Arduinos><Arduino><name>Tog</name><ip>192.168.40.3</ip><core><ArduinoMethod><name>driveForward</name><default>0</default><minimum>0</minimum><maximum>30</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>driveBackwards</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>stopTrain</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>1</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod></core><group></group></Arduino><Arduino><name>Bil</name><ip>192.168.40.4</ip><core><ArduinoMethod><name>driveForward</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>driveBackwards</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>stopTrain</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>1</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod></core><group></group></Arduino><Arduino><name>Lyskryds</name><ip>192.168.40.5</ip><core><ArduinoMethod><name>turnOnLights</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>turnOffLights</name><default>1</default><minimum>0</minimum><maximum>1</maximum><current>1</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod><ArduinoMethod><name>emergencyLights</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName></unitName><unitCount>0</unitCount></ArduinoMethod></core><group><ArduinoMethod><name>turnOnlight</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName>lyskryds</unitName><unitCount>4</unitCount></ArduinoMethod><ArduinoMethod><name>turnOfflight</name><default>0</default><minimum>0</minimum><maximum>1</maximum><current>0</current><unitName>lyskryds</unitName><unitCount>4</unitCount></ArduinoMethod></group></Arduino></Arduinos></ArduinoCollection>"); } catch (Exception ex) { Debug.WriteLine("server: " + ex); } /// her til }
public async Task ConnectAsync() { var locked = await SemaphoreSlim.WaitAsync(0, Token); // ensure no threads are reconnecting at the same time if (locked) { while (!Token.IsCancellationRequested) { try { await WebSocket.ConnectAsync(SignalWSUri).AsTask(Token); SemaphoreSlim.Release(); break; } catch (OperationCanceledException) { } catch (Exception e) { if (e.Message.Contains("(403)")) { SemaphoreSlim.Release(); throw new AuthorizationFailedException("OWS server rejected authorization."); } Logger.LogError("ConnectAsync() failed: {0}\n{1}", e.Message, e.StackTrace); //System.Runtime.InteropServices.COMException (0x80072EE7) await Task.Delay(10 * 1000); } } } }
public void Connect() { #if WINDOWS_UWP messageWebSocket.ConnectAsync(new Uri(Uri)); messageWriter = new DataWriter(messageWebSocket.OutputStream); #endif }
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) { UnicodeEncoding = UnicodeEncoding.Utf8, }; _dataWriters.Add(id, dataWriter); SendEvent("websocketOpen", new JObject { { "id", id }, }); } catch (Exception ex) { OnError(id, ex); } }
public void Connect(string address) { host = address; //Async connection. if (!con && !busy) { busy = true; Debug.Log("connecting"); Debug.Log(port); #if UNITY_EDITOR runThread = new Thread(Run); runThread.Start(); #endif # if !UNITY_EDITOR messageWebSocket = new MessageWebSocket(); messageWebSocket.Control.MessageType = SocketMessageType.Utf8; messageWebSocket.MessageReceived += Win_MessageReceived; server = new Uri("ws://" + host + ":" + port.ToString()); IAsyncAction outstandingAction = messageWebSocket.ConnectAsync(server); AsyncActionCompletedHandler aach = new AsyncActionCompletedHandler(NetworkConnectedHandler); outstandingAction.Completed = aach; #endif }
public async Task ConnectAsync(string connectionUrl) { try { await _socket.ConnectAsync(new Uri(connectionUrl)); } catch { } }
public override async Task Connect() { // TODO throw an exception if the connection was unsuccessful, goddammit await ws.ConnectAsync(ServerUri); writer = new DataWriter(ws.OutputStream); OnOpened(); }