示例#1
0
        public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription,
                                              CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            bool callClose = false;

            lock (_stateLock)
            {
                callClose = (_state != WebSocketState.CloseSent) && (_state != WebSocketState.Closed);
            }

            InterlockedCheckAndUpdateCloseState(WebSocketState.CloseSent, s_validCloseStates);

            using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
            {
                if (callClose)
                {
                    _messageWebSocket.Close((ushort)closeStatus, statusDescription ?? String.Empty);
                }

                var result = await _closeWebSocketReceiveResultTcs.Task;
                _closeStatus            = result.CloseStatus;
                _closeStatusDescription = result.CloseStatusDescription;
                InterlockedCheckAndUpdateCloseState(WebSocketState.CloseReceived, s_validCloseStates);
            }
        }
示例#2
0
    void OnDestroy()
    {
        if (ws != null)
        {
#if WINDOWS_UWP
            ws.Close(1000, "Disconnect function is called.");
#else
            ws.Close();
            ws = null;
#endif
        }
    }
示例#3
0
 private async void ws_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     try {
         // throws Exception if eof is received, which is the case for example if auth fails
         var reader  = args.GetDataReader();
         var message = reader.ReadString(reader.UnconsumedBufferLength);
         await StoreUtil.OnUiThread(() => OnMessageReceived(message));
     } catch (Exception) {
         // assumes eof has been received i.e. the server has closed the connection
         // http://msdn.microsoft.com/en-US/library/windows/apps/hh701366
         ws.Close(1005, String.Empty);
     }
 }
示例#4
0
 public async void Close()
 {
     using (var releaser = await _WebSocketLock.LockAsync())
     {
         MessageWebSocket.Close(0x8, "");
     }
 }
示例#5
0
        public static async void CloseSocket()
        {
            if (!socketIsConnected)
            {
                return;
            }

            try
            {
                socket.Close(1000, "Closed due to user request.");
                socket.Dispose();
                socket            = null;
                socketIsConnected = false;

                if (!App.isRPi)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        var currentPage       = ((ContentControl)Window.Current.Content).Content as Page;
                        var serviceStatus     = currentPage.FindName("serviceStatus") as Image;
                        serviceStatus.Opacity = 0.2;
                        var droneStatus       = currentPage.FindName("droneStatus") as Image;
                        droneStatus.Opacity   = 0.2;
                    });
                }
                else
                {
                    Debug.WriteLine("Web socket closed!");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error closing socket: " + ex.Message);
            }
        }
示例#6
0
        internal override async Task <bool> Stop(ulong timeout)
        {
            WSLOG("Stop");
            _mustStop = true;
            if (_reconnectionTimer != null)
            {
                _reconnectionTimer.Cancel();
            }

            foreach (Queue <WSRequest> queue in _workingRequests)
            {
                while (queue.Count > 0)
                {
                    WSRequest wsRequest = queue.Peek();
                    await wsRequest.getResponseBytes();

                    if (queue.Contains(wsRequest))
                    {
                        queue.Dequeue();
                    }
                }
            }

            _webSock.Close(1000, "");
            //_outDataWriter = null;
            WSLOG("Stop end");
            return(false);
        }
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (messageWebSocket != null)
                {
                    rootPage.NotifyUser("Closing", NotifyType.StatusMessage);
                    messageWebSocket.Close(1000, "Closed due to user request.");
                    messageWebSocket = null;
                }
                else
                {
                    rootPage.NotifyUser("No active WebSocket, send something first", 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";
            }
        }
        protected override void DoClose()
        {
            if (ws != null)
            {
                try
                {
                    ws.Closed -= ws_Closed;
                    //ws.MessageReceived -= ws_MessageReceived;

                    if (dataWriter != null)
                    {
                        dataWriter.Dispose();
                        dataWriter = null;
                    }

                    ws.Close(1000, "DoClose");
                    ws.Dispose();
                    ws = null;
                }
                catch (Exception e)
                {
                    var log = LogManager.GetLogger(Global.CallerName());
                    log.Info("DoClose ws.Close() Exception= " + e.Message);
                }
            }
        }
        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;
            }
        }
        private void CloseSocket()
        {
            if (messageWriter != null)
            {
                // In order to reuse the socket with another DataWriter, the socket's output stream needs to be detached.
                // Otherwise, the DataWriter's destructor will automatically close the stream and all subsequent I/O operations
                // invoked on the socket's output stream will fail with ObjectDisposedException.
                //
                // This is only added for completeness, as this sample closes the socket in the very next code block.
                messageWriter.DetachStream();
                messageWriter.Dispose();
                messageWriter = null;
            }

            if (messageWebSocket != null)
            {
                try
                {
                    messageWebSocket.Close(1000, "Closed due to user request.");
                }
                catch (Exception ex)
                {
                    AppendOutputLine(MainPage.BuildWebSocketError(ex));
                    AppendOutputLine(ex.Message);
                }
                messageWebSocket = null;
            }
        }
示例#11
0
 public void StopConnection()
 {
     if (w != null)
     {
         w.Close(1000, "Done");
     }
 }
示例#12
0
 public void UnInitialize()
 {
     if (webSocket != null)
     {
         webSocket.Close(1000, "Normal Shutdown");
     }
 }
示例#13
0
 public async void Close()
 {
     using (var releaser = await _WebSocketLock.LockAsync())
     {
         MessageWebSocket.Close(0x8, "");
         WatchingHeartbaetTimer?.Dispose();
     }
 }
示例#14
0
        internal void disconnect()
        {
            Debug.WriteLine("WSC disconnect()...");

            if (socket != null)
            {
                socket.Close(1000, "OK");
                socket    = null;
                connected = false;
            }

            /*if (keepAliveSender != null)
             * {
             *  keepAliveSender.shutdown();
             *  keepAliveSender = null;
             * }*/
        }
示例#15
0
        public void disconnect()
        {
            Debug.WriteLine("WSC disconnect()...");

            if (socket != null)
            {
                socket.Close(1000, "OK");
                socket    = null;
                connected = false;
                Closed?.Invoke(this, EventArgs.Empty);
            }

            /*if (keepAliveSender != null)
             * {
             *  keepAliveSender.shutdown();
             *  keepAliveSender = null;
             * }*/
        }
示例#16
0
        public void Close()
        {
            _DataWriter?.DetachStream();
            _DataWriter = null;

            _CommentSessionWebSocket?.Close(1000, "");
            _CommentSessionWebSocket = null;
            IsConnected = false;
        }
示例#17
0
    public void Close()
    {
#if WINDOWS_UWP
        ws.Close(1000, "Disconnect function is called.");
        ws = null;
#else
        ws.Close();
        ws = null;
#endif
    }
示例#18
0
        public Task <InvokeResult> CloseAsync()
        {
            if (_webSocket != null)
            {
                _webSocket.Close(1000, String.Empty);
                _webSocket.Dispose();
                _webSocket = null;
            }

            return(Task.FromResult(InvokeResult.Success));
        }
示例#19
0
        /// <summary>
        /// クライアント機能を停止
        /// </summary>
        public void DisconnectServer()
        {
#if UNITY_UWP
            ws.MessageReceived -= MessageReceived;
            ws.Dispose();
            ws = null;
#elif UNITY_EDITOR || UNITY_STANDALONE
            ws.OnMessage -= OnMessage;
            ws.Close();
            ws = null;
#endif
        }
示例#20
0
 public override async Task CloseAsync()
 {
     try
     {
         messageWebSocket.Close(1, "closed by user");
         await Task.CompletedTask;
     }
     catch (Exception e)
     {
         OnError?.Invoke("Close:" + e.Message);
     }
 }
示例#21
0
 public void CloseAsync()
 {
     if (socket == null)
     {
         return;
     }
     try {
         isOpened = false;
         socket.Close(1000, "User closed");
     } catch (Exception ex) {
         RaiseError(ex.Message);
     }
 }
示例#22
0
 public void Close()
 {
     if (socket != null)
     {
         try {
             socket.Close(1000, "Closed due to user request.");
         }
         catch (Exception ex) {
             OnError.Invoke(this, new ErrorEventArgs(ex.Message));
         }
         socket = null;
     }
 }
示例#23
0
        // closes the websocket connection to the ROSbridge server
        public void Disconnect()
        {
#if WINDOWS_UWP
            try
            {
                webSock.Close(0, "");
            }
            catch (System.Exception e)
            {
                Debug.Log("Exception: {Disconnect}" + e.ToString());
            }
            finally {}
#endif
        }
示例#24
0
 /// <summary>
 /// Stops listening for bridge events.
 /// </summary>
 public void StopStream()
 {
     if (running)
     {
         running = false;
         clientWriter.Dispose();
         client.Close(1000, "Closed");
         client.Dispose();
     }
     else
     {
         throw new InvalidOperationException("Bridge stream is already stopped.");
     }
 }
示例#25
0
 public void Disconnect()
 {
     try
     {
         _webSocket?.Close(0, "Disconnected");
     }
     catch
     {
         WebSocket_Closed(_webSocket, null);
     }
     finally
     {
         _webSocket = null;
     }
 }
示例#26
0
 private void CloseSocket()
 {
     if (messageWebSocket != null)
     {
         try
         {
             messageWebSocket.Close(1000, "Closed due to user request.");
         }
         catch (Exception ex)
         {
             Debug.Log(ex.Message);
         }
         messageWebSocket = null;
     }
 }
        public void Close()
        {
            if (pending != null)
            {
                pending.Dispose();
                pending = null;
            }

            if (streamWebSocket != null)
            {
                streamWebSocket.Close(1000, "Normal closure");
                streamWebSocket.Dispose();
                streamWebSocket = null;
            }
        }
 private void CloseSocket()
 {
     if (messageWebSocket != null)
     {
         try
         {
             messageWebSocket.Close(1000, "Closed due to user request.");
         }
         catch (Exception ex)
         {
             AppendOutputLine(MainPage.BuildWebSocketError(ex));
             AppendOutputLine(ex.Message);
         }
         messageWebSocket = null;
     }
 }
        public void disconnect()
        {
            Debug.WriteLine("WSC disconnect()...");

            if (socket != null)
            {
                socket.Close(1000, "None");

                socket = null;
            }

            /*if (keepAliveSender != null)
             * {
             *  keepAliveSender.shutdown();
             *  keepAliveSender = null;
             * }*/
        }
示例#30
0
        public bool CloseWebSocket()
        {
            bool worked = false;

            if (webSocket != null)
            {
                try
                {
                    webSocket.Close(0, "App Closing");
                    worked = true;
                }
                catch (Exception)
                { }
                webSocket = null;
            }

            return(worked);
        }