Пример #1
0
        public async Task Connect()
        {
            Protocol = new Protocol(true);

            socket = new Websocket(Receive);

            ApiToken = await FFB.Instance.Api.GetToken();

            try
            {
                string uri = "ws://fumbbl.com:22223/command";
                //string uri = "ws://localhost:22227/command";

                await Task.Delay(100);

                LogManager.Info($"Networking Connecting to {uri}");
                MainHandler.Instance.AddReport(RawString.Create($"Connecting to {uri}"));
                await socket.Connect(uri);

                LogManager.Debug("Networking Connected");

                RequestVersion();
            }
            catch (Exception e)
            {
                LogManager.Error($"<style=\"Error\">Error connecting: {e.Message}</style>");
                MainHandler.Instance.AddReport(RawString.Create($"<style=\"Error\">Error connecting: {e.Message}</style>"));
            }
        }
Пример #2
0
        /// <summary>
        /// Handler for a socket closing. Reconnects the socket if needed, or removes it from the active socket list if not
        /// </summary>
        /// <param name="socket">The socket that was closed</param>
        protected virtual void SocketOnClose(IWebsocket socket)
        {
            if (socket.ShouldReconnect)
            {
                if (socket.Reconnecting)
                {
                    return; // Already reconnecting
                }
                socket.Reconnecting = true;

                log.Write(LogVerbosity.Info, $"Socket {socket.Id} Connection lost, will try to reconnect");
                Task.Run(() =>
                {
                    Thread.Sleep(ReconnectInterval);
                    socket.Reset();

                    if (!socket.Connect().Result)
                    {
                        log.Write(LogVerbosity.Debug, $"Socket {socket.Id} failed to reconnect");
                        return; // Connect() should result in a SocketClosed event so we end up here again
                    }
                    var time = socket.DisconnectTime;
                    socket.DisconnectTime = null;
                    if (time == null)
                    {
                        return;
                    }

                    log.Write(LogVerbosity.Info, $"Socket {socket.Id} reconnected after {DateTime.UtcNow - time}");

                    SocketSubscription subscription;
                    lock (sockets)
                        subscription = sockets.Single(s => s.Socket == socket);

                    socket.Reconnecting = false;
                    if (!SocketReconnect(subscription, DateTime.UtcNow - time.Value))
                    {
                        socket.Close().Wait(); // Close so we end up reconnecting again
                    }
                    else
                    {
                        log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed");
                    }
                });
            }
            else
            {
                log.Write(LogVerbosity.Info, $"Socket {socket.Id} closed");
                socket.Dispose();
                lock (sockets)
                {
                    var subscription = sockets.SingleOrDefault(s => s.Socket.Id == socket.Id);
                    if (subscription != null)
                    {
                        sockets.Remove(subscription);
                    }
                }
            }
        }
        private async Task <bool> Open()
        {
            bool connectResult = await socket.Connect().ConfigureAwait(false);

            if (!connectResult)
            {
                log.Write(LogVerbosity.Warning, "Couldn't connect to socket");
                return(false);
            }

            running = true;
#pragma warning disable 4014
            Task.Run(() => ProcessData());
            Task.Run(() => ProcessSending());
#pragma warning restore 4014
            log.Write(LogVerbosity.Info, "Socket connection established");
            return(true);
        }
Пример #4
0
        protected override void OnStart(IConnection con, string conData, CancellationToken disconToken)
        {
            connection     = con;
            connectionData = conData;

            var connectUrl = UrlBuilder.BuildConnect(connection, Name, connectionData);

            if (websocket != null)
            {
                DisposeWebSocket();
            }

            // SignalR uses https, websocket4net uses wss
            connectUrl = connectUrl.Replace("http://", "ws://").Replace("https://", "wss://");

            IDictionary <string, string> cookies = new Dictionary <string, string>();

            if (connection.CookieContainer != null)
            {
                var container = connection.CookieContainer.GetCookies(new Uri(connection.Url));
                foreach (Cookie cookie in container)
                {
                    cookies.Add(cookie.Name, cookie.Value);
                }
            }

            websocket                       = new BaseSocket(log, connectUrl, cookies, connection.Headers);
            websocket.OnError              += WebSocketOnError;
            websocket.OnClose              += WebSocketOnClosed;
            websocket.OnMessage            += WebSocketOnMessageReceived;
            websocket.DataInterpreterString = interpreter;

            if (connection.Proxy != null)
            {
                var proxy = connection.Proxy.GetProxy(new Uri(connectUrl));
                websocket.SetProxy(proxy.Host, proxy.Port);
            }

            if (!websocket.Connect().Result)
            {
                TransportFailed(new Exception("Can't connect"));
            }
        }
        private void PerformConnect(string url)
        {
            if (websocket != null)
            {
                DisposeWebSocket();
            }

            webSocketTokenSource = new CancellationTokenSource();
            webSocketTokenSource.Token.Register(WebSocketTokenSourceCanceled);
            CancellationTokenSource.CreateLinkedTokenSource(webSocketTokenSource.Token, disconnectToken);

            // SignalR uses https, websocket4net uses wss
            url = url.Replace("http://", "ws://").Replace("https://", "wss://");

            IDictionary <string, string> cookies = new Dictionary <string, string>();

            if (connection.CookieContainer != null)
            {
                var container = connection.CookieContainer.GetCookies(new Uri(connection.Url));
                foreach (Cookie cookie in container)
                {
                    cookies.Add(cookie.Name, cookie.Value);
                }
            }

            websocket            = new BaseSocket(url, cookies, connection.Headers);
            websocket.OnError   += WebSocketOnError;
            websocket.OnOpen    += WebSocketOnOpened;
            websocket.OnClose   += WebSocketOnClosed;
            websocket.OnMessage += WebSocketOnMessageReceived;

            if (connection.Proxy != null)
            {
                var proxy = connection.Proxy.GetProxy(new Uri(url));
                websocket.SetProxy(proxy.Host, proxy.Port);
            }

            websocket.Connect().Wait(webSocketTokenSource.Token);
        }
Пример #6
0
        public void Connect()
        {
            // connectClock++;
            if (Conn != null)
            {
                return;
            }

            _closeWasClean = false;

            var config = new WebsocketConfiguration
            {
                uri               = EndPointUrl(),
                onOpenCallback    = OnConnOpen,
                onCloseCallback   = OnConnClose,
                onErrorCallback   = OnConnError,
                onMessageCallback = OnConnMessage
            };

            Conn = _websocketFactory.Build(config);

            Conn.Connect();
        }