Exemplo n.º 1
0
 /// <summary>
 /// Disconnect and clean-up.
 /// </summary>
 /// <returns>True when completed.</returns>
 public async Task <bool> DisconnectAsync(bool cancelExisting = true)
 {
     if (cancelExisting)
     {
         connectionCancellation?.Cancel(true);
     }
     if (_Client != null && _Client.State == WebSocketState.Open)
     {
         try
         {
             await _Client.CloseAsync(WebSocketCloseStatus.Empty, null, CancellationToken.None).ConfigureAwait(false);
         }
         catch (WebSocketException e)
         {
             OnErrorState(e, -1);
         }
     }
     if (_Client != null)
     {
         OnStateChange(_Client.State);
         _Client?.Abort();
         _Client?.Dispose();
         _Client = null;
     }
     else
     {
         OnStateChange(WebSocketState.None);
     }
     return(true);
 }
        public async Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType)
        {
            CheckDisposing();

            if (!IsConnected || buffer == null || buffer.Array.Length == 0)
            {
                return;
            }

            await _sendSemph.WaitAsync().ConfigureAwait(false);

            try
            {
                await _client
                .SendAsync(
                    buffer,
                    WebSocketMessageType.Text,
                    true,
                    _cancelTokenSource.Token)
                .ConfigureAwait(false);
            }
            catch
            {
                _client.Abort();
                LogError("Connection to the server was unexpectedly interrupted on \"SendAsync\"");
            }
            finally
            {
                _sendSemph.Release();
            }
        }
Exemplo n.º 3
0
        protected override void ActionCore()
        {
            while (!IsCancelled())
            {
                Connected = false;
                using (ClientWebSocket webSocket = new ClientWebSocket())
                {
                    try
                    {
                        Task connectTask = webSocket.ConnectAsync(Uri, _token);
                        connectTask.Wait(_token);
                    }
                    catch (AggregateException)
                    {
                        Thread.Sleep(ConnectionSpan);
                        continue;
                    }
                    catch (OperationCanceledException)
                    {
                        webSocket.Abort();
                        break;
                    }

                    LogPool.Logger.LogInformation((int)LogEvent.套接字, $"ws_connect {Uri}");
                    Connected = true;
                    byte[]      buffer = new byte[10 * 1024];
                    List <byte> packet = new List <byte>();
                    while (!IsCancelled())
                    {
                        try
                        {
                            Task <WebSocketReceiveResult> receiveTask =
                                webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), _token);
                            receiveTask.Wait(_token);
                            packet.AddRange(buffer.Take(receiveTask.Result.Count));
                            if (receiveTask.Result.EndOfMessage)
                            {
                                WebSocketReceived?.Invoke(this, new WebSocketReceivedEventArges
                                {
                                    Packet = packet,
                                    Uri    = Uri
                                });
                                packet.Clear();
                            }
                        }
                        catch (AggregateException)
                        {
                            LogPool.Logger.LogInformation((int)LogEvent.套接字, $"ws_shutdown {Uri}");
                            break;
                        }
                        catch (OperationCanceledException)
                        {
                            webSocket.Abort();
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 4
0
 private void OnDestroy()
 {
     if (!isWebGLPlatform && connected && socket != null)
     {
         socket.Abort();
         socket.Dispose();
     }
 }
 public void Dispose()
 {
     _disposing = true;
     Log.Debug(L("Disposing.."));
     _lastChanceTimer?.Dispose();
     _cancelation?.Cancel();
     _client?.Abort();
     _client?.Dispose();
     _cancelation?.Dispose();
 }
Exemplo n.º 6
0
        private void Monitor()
        {
            Log($"Starting monitor.");
            _tokenSource = new CancellationTokenSource();
            while (RunMonitor)
            {
                do
                {
                    InitializeClient();

                    Uri url = new Uri(Url);
                    try
                    {
                        _reconnecting = true;

                        if (_disconnectCalled == true)
                        {
                            _disconnectCalled = false;
                            Log("Re-connecting closed connection.");
                        }

                        _ws.ConnectAsync(url, _tokenSource.Token).Wait(15000);
                    }
                    catch (Exception e)
                    {
                        Log(e.Message);
                        _ws.Abort();
                        _ws.Dispose();
                        Thread.Sleep(_options.MyReconnectStrategy.GetReconnectInterval() - 1000);
                    }
                } while (RunMonitor && _ws.State != WebSocketState.Open);
                _reconnecting = false;
                Console.WriteLine("Starting Listener & Sender tasks.");
                StartListener();
                StartSender();
                OnOpened?.Invoke();
                while (_ws.State == WebSocketState.Open)
                {
                    Thread.Sleep(200);
                }
                _reconnecting = true;
                for (int i = 0; i < 10; i++)
                {
                    if ((_listenerRunning || _senderRunning) == false)
                    {
                        break;
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            MonitorFinished = true;
        }
        public void Stop()
        {
            _disposing = true;
            Console.WriteLine(L("Stop.."));

            _lastChanceTimer?.Dispose();
            _cancelation?.Cancel();
            _client?.Abort();
            _client?.Dispose();
            _cancelation?.Dispose();
        }
 /// <summary>
 /// Terminate the websocket connection and cleanup everything
 /// </summary>
 public void Dispose()
 {
     _disposing = true;
     Log.Debug(L("Disposing.."));
     _lastChanceTimer?.Dispose();
     _cancelation?.Cancel();
     _cancelationTotal?.Cancel();
     _client?.Abort();
     _client?.Dispose();
     _cancelation?.Dispose();
     _cancelationTotal?.Dispose();
     _messagesToSendQueue?.Dispose();
     IsStarted = false;
 }
Exemplo n.º 9
0
 public void StopObserve()
 {
     if (webSocket.State == WebSocketState.Open)
     {
         webSocket.Abort();
     }
 }
Exemplo n.º 10
0
 public void Disconnect()
 {
     ClearLoops();
     try {
         client.Abort();
     } catch {}
 }
Exemplo n.º 11
0
 public void Dispose()
 {
     _cts.Cancel();
     _webSocketListener.Wait();
     _webSocket.Abort();
     _webSocket.Dispose();
 }
Exemplo n.º 12
0
 public Task CloseAsync()
 {
     if (_socket == null)
     {
         throw new InvalidOperationException("Close failed, must connect first.");
     }
     else
     {
         _tokenSource.Cancel();
         _tokenSource.Dispose();
         _socket.Abort();
         _receiverLoop.Abort();
         _senderLoop.Abort();
         _socket.Dispose();
         WakeSenderLoop();
         State   = SocketState.Closed;
         _socket = null;
         if (serverCloseReason != ServerCloseReason.SocketClosedByClient)
         {
             OnClosed?.Invoke(serverCloseReason);
         }
         else
         {
             OnClosed?.Invoke(ServerCloseReason.SocketClosedByClient);
         }
         // SocketClosedByClient
         return(Task.CompletedTask);
     }
 }
        public async Task ConnectAsync()
        {
            do
            {
                try
                {
                    await mWebSocket.ConnectAsync(mAddressUri, mCancellationToken)
                    .ConfigureAwait(false);

                    Task task = Task.Run(this.RunAsync, mCancellationToken);
                    break;
                }
                catch (WebSocketException wex)
                {
                    mWebSocket.Abort();
                    mWebSocket = new ClientWebSocket();
                    Debug.WriteLine("websocket exception ");
                }
                catch (Exception ex)
                {
                    RaiseConnectionError(ex);
                    RaiseConnectionClosed();
                    break;
                }
            } while (true);
        }
Exemplo n.º 14
0
 public void Disconnect()
 {
     try
     {
         if (cancellationTokenSource != null)
         {
             cancellationTokenSource.Cancel();
         }
         if (webSocket != null)
         {
             webSocket.Abort();
             webSocket.Dispose();
             Console.WriteLine($"\n{NameProvider} WebSocket Close.");
         }
         if (timerIsPing != null)
         {
             timerIsPing.Dispose();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Disconnect error: " + ex);
     }
     finally
     {
         webSocket = null;
         cancellationTokenSource = null;
         timerIsPing             = null;
         IsConnected             = false;
     }
 }
Exemplo n.º 15
0
        // 关闭连接
        public Task Close()
        {
            if (_Response.State == SocketState.Connect)
            {
                if (_TokenSource != null)
                {
                    _TokenSource.Cancel();
                    _TokenSource.Dispose();
                }

                _TokenSource = null;

                if (_Response.State != SocketState.Close)
                {
                    _Response.State = SocketState.Close;
                    _EventTarget.Emit(SocketStockEvent.Close);
                }
                if (_Socket != null)
                {
                    _Socket.Abort();
                    _Socket.Dispose();
                }
                _Socket = null;

                _Request  = null;
                _Response = null;
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 16
0
        public async Task Receive(DialogContext dc)
        {
            try
            {
                ArraySegment <byte>    receivedBytes = new ArraySegment <byte>(new byte[1024]);
                WebSocketReceiveResult result        = await ws.ReceiveAsync(receivedBytes, CancellationToken.None);

                Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count));
                var    jsonObj = JObject.Parse(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count));
                string method  = JObject.Parse(jsonObj.ToString())["body"]["method"].ToString();
                if (method.ToString() == "newMessage")
                {
                    var message = JObject.Parse(jsonObj.ToString())["body"]["message"].ToString();
                    await dc.Context.SendActivityAsync(message.ToString());
                }
                else
                if (method.ToString() == "participantLeave")
                {
                    agentchatstarted = 0;
                    await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "closing WS", CancellationToken.None);

                    Console.WriteLine("WebSocket closed." + ws.CloseStatus);
                    ws.Abort();
                    chatdata.Clear();
                    await dc.Context.SendActivityAsync("chat has been closed");
                }
                else
                if (method.ToString() == "newParticipant")
                {
                    await dc.Context.SendActivityAsync("Agent joined.");
                }
            }
            catch (Exception ex)
            { }
        }
        public Task CloseAsync(WebSocketCloseStatus webSocketCloseStatus = WebSocketCloseStatus.NormalClosure, string reason = "Passive Closure")
        {
            SpeechWebSocketLogger.Log("### SpeechWebSocket.STATUS: {0} ###", ClientWebSocket.State);

            switch (ClientWebSocket.State)
            {
            case WebSocketState.Closed:
            case WebSocketState.None:
                ReceiveTokenSource?.Cancel();
                return(Task.CompletedTask);

            case WebSocketState.Aborted:
            case WebSocketState.CloseReceived:
                SendingTokenSource?.Cancel();
                return(Task.CompletedTask);

            case WebSocketState.CloseSent:
                SendingTokenSource?.Cancel();
                return(ClientWebSocket.CloseAsync(webSocketCloseStatus, reason, CancellationToken.None));

            case WebSocketState.Connecting:
                ReceiveTokenSource?.Cancel();
                ClientWebSocket.Abort();
                return(Task.CompletedTask);

            case WebSocketState.Open:
            default:
                SendingTokenSource?.Cancel();
                return(ClientWebSocket.CloseOutputAsync(webSocketCloseStatus, reason, CancellationToken.None));
            }
        }
Exemplo n.º 18
0
 public void Stop()
 {
     _logger.Debug("Stop WebSocket");
     _cancelToken.Cancel();
     _socket.Abort();
     _socket.Dispose();
 }
Exemplo n.º 19
0
        private async void SendDataToServer()
        {
            if (DevicePicker.SelectedItem is null)
            {
                return;
            }

            ClientWebSocket client = new ClientWebSocket();

            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(10000);

                await client.ConnectAsync(new Uri($"ws://{DevicePicker.SelectedItem.ToString()}:12345"), cts.Token);

                await client.SendAsync(new ArraySegment <byte>(Data.ToByteArray()), WebSocketMessageType.Text, true, cts.Token);

                await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", cts.Token);
            }
            catch (Exception ex)
            {
                client.Abort();
                await DisplayAlert("Error", "Could not connect: " + ex.Message, "Ok");
            }
        }
Exemplo n.º 20
0
        internal async Task <IAsyncTransport> ConnectAsync(Address address, Action <ClientWebSocketOptions> options)
        {
            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port   = GetDefaultPort(address.Scheme, address.Port),
                Host   = address.Host,
                Path   = address.Path
            }.Uri;

            ClientWebSocket cws = new ClientWebSocket();

            cws.Options.AddSubProtocol(WebSocketSubProtocol);
            if (options != null)
            {
                options(cws.Options);
            }

            await cws.ConnectAsync(uri, CancellationToken.None);

            if (cws.SubProtocol != WebSocketSubProtocol)
            {
                cws.Abort();

                throw new NotSupportedException(
                          string.Format(
                              CultureInfo.InvariantCulture,
                              "WebSocket SubProtocol used by the host is not the same that was requested: {0}",
                              cws.SubProtocol ?? "<null>"));
            }

            this.webSocket = cws;

            return(this);
        }
Exemplo n.º 21
0
        private async Task InternalDisconnect(WebSocketCloseStatus status, string reason = "UNKNOWN", bool isUserInvoked = false)
        {
            // Only do this once.
            if (State == SimpleWebySocketState.Disconnected)
            {
                return;
            }

            // First of set the new state.
            UpdateState(SimpleWebySocketState.Disconnected, isUserInvoked);

            // Now try to close the web socket.
            ClientWebSocket ws = m_ws;

            if (ws != null)
            {
                try
                {
                    await ws.CloseAsync(status, reason, m_cancelToken.Token);
                }
                catch (Exception) { }

                try
                {
                    ws.Abort();
                }
                catch (Exception) { }
            }

            // Cancel anything that's not dead.
            m_cancelToken.Cancel();
        }
            static async Task ProcessAsync(WebSocketAdapter webSocket, Behavior behavior, ClientWebSocket?client = null, HttpContext?context = null)
            {
                if (behavior == Behavior.SendsClose_WaitsForClose ||
                    behavior == Behavior.SendsClose_ClosesConnection)
                {
                    await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Bye");
                }

                if (behavior == Behavior.SendsClose_WaitsForClose ||
                    behavior == Behavior.WaitsForClose_SendsClose ||
                    behavior == Behavior.WaitsForClose_ClosesConnection)
                {
                    await ReceiveAllMessagesAsync(webSocket);
                }

                if (behavior == Behavior.WaitsForClose_SendsClose)
                {
                    await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Bye");
                }

                if (behavior.HasFlag(Behavior.ClosesConnection))
                {
                    client?.Abort();

                    if (context is not null)
                    {
                        await context.Response.Body.FlushAsync();

                        context.Abort();
                    }
                }
            }
Exemplo n.º 23
0
        private async Task EventLoop()
        {
            var token = _eventLoopCancellation.Token;

            var buffer       = new byte[RECEIVE_CHUNK_SIZE];
            var segment      = new ArraySegment <byte>(buffer);
            var memoryStream = new MemoryStream();

            // Connect socket.
            await _socket.ConnectAsync(_uri, token);

            // Run event loop.
            try
            {
                await(OnConnect?.Invoke() ?? Task.CompletedTask);

                // Receive messages.
                while (WebSocketState.Open == _socket.State)
                {
                    WebSocketReceiveResult received;
                    do
                    {
                        received = await _socket.ReceiveAsync(segment, token);

                        memoryStream.Write(buffer, 0, received.Count); // Don't use async, memoryStream doesn't do IO.
                    }while (!received.EndOfMessage);

                    // Trigger event. ToArray makes copy of buffer.
                    await(OnMessage?.Invoke(memoryStream.ToArray()) ?? Task.CompletedTask);

                    // Reset memoryStream (also sets the position to zero).
                    memoryStream.SetLength(0);
                }
            }
            finally
            {
                // Trigger OnDisconnect.
                try
                {
                    await(OnDisconnect?.Invoke() ?? Task.CompletedTask);
                }
                finally
                {
                    // Close Socket.
                    try
                    {
                        await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, token);
                    }
                    catch
                    {
                        _socket.Abort();
                    }
                    finally
                    {
                        _socket.Dispose();
                    }
                }
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Aborts this socket.
 /// </summary>
 public void Abort()
 {
     if (socket != null)
     {
         disconnectInitiated = true;
         socket.Abort();
     }
 }
Exemplo n.º 25
0
 private void Close()
 {
     try
     {
         Socket.Abort();
     }
     catch (Exception) { }
 }
Exemplo n.º 26
0
        public void ClientWebSocket_NoConnect_AbortCalled_Ok()
        {
            var cws = new ClientWebSocket();

            cws.Abort();

            Assert.Equal(WebSocketState.Closed, cws.State);
        }
Exemplo n.º 27
0
 void OnDestroy()
 {
     if (webSocket != null)
     {
         webSocket.Abort();
         webSocket.Dispose();
     }
     Debug.Log("WebSocket disposed.");
 }
Exemplo n.º 28
0
 protected override void AbortInternal()
 {
     if (!disposed && webSocket.State != WebSocketState.Aborted)
     {
         disposed = true;
         webSocket.Abort();
         webSocket.Dispose();
     }
 }
Exemplo n.º 29
0
        public void Abort_CreateAndAbort_StateIsClosed()
        {
            using (var cws = new ClientWebSocket())
            {
                cws.Abort();

                Assert.Equal(WebSocketState.Closed, cws.State);
            }
        }
Exemplo n.º 30
0
        public void Abort_CreateAndDisposeAndAbort_StateIsClosedSuccess()
        {
            var cws = new ClientWebSocket();

            cws.Dispose();

            cws.Abort();
            Assert.Equal(WebSocketState.Closed, cws.State);
        }
Exemplo n.º 31
0
        public void Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server)
        {
            using (var cws = new ClientWebSocket())
            {
                var cts = new CancellationTokenSource(TimeOutMilliseconds);

                var ub = new UriBuilder(server);
                ub.Query = "delay10sec";

                Task t = cws.ConnectAsync(ub.Uri, cts.Token);
                cws.Abort();
                WebSocketException ex = Assert.Throws<WebSocketException>(() => t.GetAwaiter().GetResult());

                Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);

                Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
                Assert.Equal(WebSocketState.Closed, cws.State);
            }
        }
Exemplo n.º 32
-2
        public void Abort_CreateAndAbort_StateIsClosed()
        {
            var cws = new ClientWebSocket();
            cws.Abort();

            Assert.Equal(WebSocketState.Closed, cws.State);
        }