예제 #1
0
        public void Setup()
        {
            factory           = A.Fake <IConnectionFactory>();
            fakeHttp          = A.Fake <ISimpleHttpGetRequest>();
            fakeWebSocket     = A.Fake <IWebSocket>();
            heartBeatSignaler = A.Fake <IHeartBeatSignaler>();

            A.CallTo(() => factory.CreateHttpRequest(A <string> ._)).Returns(fakeHttp);
            A.CallTo(() => fakeHttp.Execute()).ReturnsLazily(() => handshakeResponse);
            A.CallTo(() => factory.CreateWebSocket(A <string> ._)).Returns(fakeWebSocket);
            A.CallTo(() => fakeWebSocket.Connected).ReturnsLazily(() => isConnected);

            A.CallTo(() => fakeWebSocket.Open()).Invokes(() =>
            {
                isConnected           = true;
                fakeWebSocket.Opened += Raise.With(fakeWebSocket, EventArgs.Empty).Now;
            });

            A.CallTo(() => fakeWebSocket.Close()).Invokes(() =>
            {
                isConnected           = false;
                fakeWebSocket.Closed += Raise.With(fakeWebSocket, EventArgs.Empty).Now;
            });

            io = new SocketIOClient(factory, heartBeatSignaler);

            socket = io.Connect("http://localhost:3000");
        }
예제 #2
0
        /// <summary>
        /// Handles reconnections in the event of connection loss
        /// </summary>
        protected virtual void Reconnect()
        {
            if (WebSocket.IsOpen)
            {
                // connection is still good
                LastHeartbeatUtcTime = DateTime.UtcNow;
                return;
            }

            Log.Trace($"BaseWebsocketsBrokerage(): Reconnecting... IsConnected: {IsConnected}");
            var subscribed = GetSubscribed();

            WebSocket.Error -= this.OnError;
            try
            {
                //try to clean up state
                if (IsConnected)
                {
                    WebSocket.Close();
                    Wait(_connectionTimeout, () => !WebSocket.IsOpen);
                }
                if (!IsConnected)
                {
                    WebSocket.Connect();
                    Wait(_connectionTimeout, () => WebSocket.IsOpen);
                }
            }
            finally
            {
                WebSocket.Error += this.OnError;
                this.Subscribe(subscribed);
            }
        }
예제 #3
0
      public void Setup()
      {
         factory = A.Fake<IConnectionFactory>();
         fakeHttp = A.Fake<ISimpleHttpGetRequest>();
         fakeWebSocket = A.Fake<IWebSocket>();
         heartBeatSignaler = A.Fake<IHeartBeatSignaler>();

         A.CallTo(() => factory.CreateHttpRequest(A<string>._)).Returns(fakeHttp);
         A.CallTo(() => fakeHttp.Execute()).ReturnsLazily(() => handshakeResponse);
         A.CallTo(() => factory.CreateWebSocket(A<string>._)).Returns(fakeWebSocket);
         A.CallTo(() => fakeWebSocket.Connected).ReturnsLazily(() => isConnected);

         A.CallTo(() => fakeWebSocket.Open()).Invokes(() =>
         {
            isConnected = true;
            fakeWebSocket.Opened += Raise.With(fakeWebSocket, EventArgs.Empty).Now;
         });

         A.CallTo(() => fakeWebSocket.Close()).Invokes(() =>
         {
            isConnected = false;
            fakeWebSocket.Closed += Raise.With(fakeWebSocket, EventArgs.Empty).Now;
         });

         io = new SocketIOClient(factory, heartBeatSignaler);

         socket = io.Connect("http://localhost:3000");
      }
예제 #4
0
 public void Dispose()
 {
     if (_ws != null && IsConnected)
     {
         _ws.Close();
         IsConnected = false;
         _ws         = null;
     }
 }
 private void closeSocket(IWebSocket webSocket)
 {
     try
     {
         webSocket.Close(1000, "Closed due to user request.");
     }
     catch (Exception ex)
     {
     }
 }
예제 #6
0
 private void closeSocket(IWebSocket webSocket)
 {
     try
     {
         webSocket.Close(1000, "Closed due to user request.");
     }
     catch (Exception ex)
     {
         AppInsights.Client.TrackException(ex);
     }
 }
예제 #7
0
        public void Connect()
        {
            string url;

            if (this.encrypted || this.secure)
            {
                url = "wss://" + Pusher.host + ":" + Pusher.wss_port + this.path;
            }
            else
            {
                url = "ws://" + Pusher.host + ":" + Pusher.ws_port + this.path;
            }

            Pusher.allow_reconnect = true;
            Pusher.Log("Pusher : connecting : " + url);

            var self = this;

            IWebSocket ws = CreateWebSocket(url);

            // Timeout for the connection to handle silently hanging connections
            // Increase the timeout after each retry in case of extreme latencies
            int interval = Pusher.connection_timeout + (this.retry_counter * 1000);

            var timerRef = new TimerRef();

            timerRef.Ref = new Timer(delegate(object state)
            {
                Pusher.Log("Pusher : connection timeout after " + interval + "ms");
                ws.Close();
                try { timerRef.Ref.Dispose(); }
                catch { }
            }, null, interval, interval);

            ws.OnData  += (sender, e) => OnMessage(e);
            ws.OnClose += (sender, e) =>
            {
                try { timerRef.Ref.Dispose(); }
                catch { }
                OnClose();
            };
            ws.OnOpen += (sender, e) =>
            {
                try { timerRef.Ref.Dispose(); }
                catch { }
                OnOpen();
            };

            this.connection = ws;

            ws.Open();
        }
예제 #8
0
        public void TestDisposeClosesWebSocketIfConnected()
        {
            WebSocketJetConnection webSocketJetConnection = new WebSocketJetConnection("ws://172.19.191.179:8081");
            IWebSocket             webSocket = WebSocketFakesFactory.CreateWebSocketThatConnectsAndClosesSuccessful();

            webSocketJetConnection.SetWebSocket(webSocket);
            webSocketJetConnection.Connect(A.Dummy <Action <bool> >(), 1000.0);

            webSocketJetConnection.Dispose();

            A.CallTo(() => webSocket.Close(CloseStatusCode.Away)).MustHaveHappened(Repeated.Exactly.Once).Then(
                A.CallTo(() => webSocket.Dispose()).MustHaveHappened(Repeated.Exactly.Once));
        }
예제 #9
0
        public void TestConnectTimeoutClosesWebSocketIfAlive()
        {
            WebSocketJetConnection webSocketJetConnection = new WebSocketJetConnection("ws://172.19.191.179:8081");
            ITimer     timer     = A.Fake <ITimer>();
            IWebSocket webSocket = WebSocketFakesFactory.CreateWebSocketThatFailsConnectDueTimeout(timer);

            webSocketJetConnection.SetWebSocket(webSocket);
            webSocketJetConnection.ConnectTimer = timer;
            A.CallTo(() => webSocket.IsAlive).Returns(true);
            webSocketJetConnection.Connect(A.Dummy <Action <bool> >(), 1000.0);

            A.CallTo(() => webSocket.Close()).MustHaveHappened(Repeated.Exactly.Once);
        }
예제 #10
0
        public void Disconnect()
        {
            if (mSocketClient == null)
            {
                return;
            }

            var state = mSocketClient.GetState();

            if (state == WebSocketState.Connecting || state == WebSocketState.Open)
            {
                mSocketClient.Close();
            }
            mSocketClient = null;
        }
        public void Disconnect()
        {
            var wasConnected = Connected || Connecting;

            if (wasConnected)
            {
                m_heartBeatSignaler.Stop();

                Of(DefaultNamespace).Emit("disconnect");

                m_socket.Close();

                EmitLocally("disconnect", "booted");
            }
        }
예제 #12
0
        private void CloseSync()
        {
            var resetEvent = new ManualResetEvent(false);
            EventHandler <WebSocketCloseData> triggerEvent = (o, args) => resetEvent.Set();

            WebSocket.Closed += triggerEvent;

            WebSocket.Close();

            if (!resetEvent.WaitOne(ConnectionTimeout))
            {
                throw new TimeoutException("Websocket close timeout.");
            }
            WebSocket.Closed -= triggerEvent;
        }
예제 #13
0
        /// <summary>
        /// 处理SockJs消息
        /// </summary>
        /// <param name="msg"></param>
        private void TransportMessage(string msg)
        {
            if (msg == null || msg.Length < 1)
            {
                return;
            }

            string type    = msg.Substring(0, 1);
            string content = msg.Substring(1);

            // first check for messages that don't need a payload
            switch (type)
            {
            case "o":    //连接已打开
                this.SockJsOpen();
                return;

            case "h":    //心跳
                //这里待实现
                //javascript src:
                //this.dispatchEvent(new Event('heartbeat'));
                //debug('heartbeat', this.transport);
                return;
            }

            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            JToken payload = null;

            try
            {
                payload = JToken.Parse(content);
            }
            catch (Exception ex)
            {
                Debug("sockjs payload bad json:" + ex.Message);
                return;
            }

            switch (type)
            {
            case "a":    //array message
                if (payload is JArray)
                {
                    foreach (var item in payload)
                    {
                        Debug("message:" + item);
                        this.OnMessageReceived(item.ToString());
                    }
                    ;
                }
                break;

            case "m":    //message
                Debug("message" + payload);
                this.OnMessageReceived(payload.ToString());
                break;

            case "c":    //close
                if ((payload is JArray) && payload.Count() == 2)
                {
                    websocket.Close(ushort.Parse(payload[0].ToString()), payload[1].ToString());
                }
                break;
            }
        }
예제 #14
0
 public void Disconnect()
 {
     socket.Close();
 }
예제 #15
0
 /// <summary>
 /// Closes the websocket connection
 /// </summary>
 public Task Close(WebSocketCloseStatus status, string reason)
 {
     return(mWebSocket.Close(status, reason, CancellationToken.None));
 }
예제 #16
0
 /// <summary>
 /// Close a WebSocket connection
 /// </summary>
 public void Close()
 {
     _timer.Stop();
     _ws.Close();
 }
예제 #17
0
 /// <summary>
 /// Closes connection to a streaming API.
 /// </summary>
 public void Disconnect() => _webSocket.Close();