Exemplo n.º 1
0
        private void SendPing(int tries)
        {
            if (tries <= 0)
            {
                if (_ping.Received)
                {
                    Console.WriteLine("Pong received!");
                    Connected = true;
                    ConnectionSuccessful?.Invoke(this);
                }
                else
                {
                    Console.WriteLine("Ping did not come back on time.");
                    Connected = false;
                    ConnectionFailed?.Invoke(this, null);
                    return;
                }
            }

            Task.Run(() => {
                _ping         = new Ping();
                string pingID = _ping.ID;

                Send(_ping);
                Thread.Sleep(200);

                if (_ping.ID == pingID && !_ping.Received)
                {
                    SendPing(--tries);
                }
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Connect the controller to the light bridge.
        /// </summary>
        internal async Task <bool> Connect()
        {
            // Connect to the Philips Hue bridge.  If we ever change lights the Hue stuff can be abstracted out.
            if (Simulator != null)
            {
                Simulator.Log("Connection");
                return(true);
            }
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            if (bridges == null || bridges.Count() == 0)
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
                return(false);
            }
            bridge = bridges.ElementAt(0);
            client = new LocalHueClient(bridge.IpAddress);
            // var appKey = await client.RegisterAsync("light-control", "fela");
            client?.Initialize(apiKey);
            bool connected = await client?.CheckConnection();

            if (client != null && connected)
            {
                Connected?.Invoke(this, new EventArgs());
            }
            else
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
            }
            return(connected);
        }
Exemplo n.º 3
0
        public bool Connect(string host, int port, string password)
        {
            Connecting?.Invoke(this, EventArgs.Empty);

            try
            {
                if (!rcon.Connect(host, port))
                {
                    throw new Exception("Connection to server failed. Check your host and port.");
                }

                if (!rcon.Authenticate(password))
                {
                    Disconnect();
                    throw new Exception("Authentication with server failed. The password is incorrect.");
                }
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, ex.Message);
                throw;
            }

            Connected?.Invoke(this, EventArgs.Empty);

            return(true);
        }
Exemplo n.º 4
0
 protected override void HandleConnectedFailed(string error)
 {
     base.IsConnected = false;
     errorHandled     = true;
     base.HandleConnectedFailed(error);
     ConnectionFailed?.Invoke(this, error);
 }
Exemplo n.º 5
0
        public void Receive(int bufferSize)
        {
            if (!Connected)
            {
                return;
            }

            Task.Run( // Initiate the receiver thread
                () => {
                bool error = false;
                do
                {
                    if (!TryReceiveOnce(out Packet packet))
                    {
                        error = true;
                        ConnectionFailed?.Invoke(this, null);
                    }

                    if (packet != null)
                    {
                        packet.ParseFailed += PacketParseFailed;
                    }

                    DataReceived?.Invoke(this, packet);
                } while (Connected && !error);
            }
                );
        }
Exemplo n.º 6
0
 /// <summary>
 /// Connect
 /// </summary>
 public void Connect()
 {
     new Thread(delegate()
     {
         PingReply pingReply = null;
         try
         {
             if (timeout > 0)
             {
                 pingReply = new Ping().Send("live.bilibili.com", timeout);
             }
             else
             {
                 pingReply = new Ping().Send("live.bilibili.com");
             }
         }
         catch (Exception)
         {
         }
         if (pingReply == null || pingReply.Status != IPStatus.Success)
         {
             ConnectionFailed?.Invoke("网络连接失败");
             return;
         }
         DanmakuServer danmakuServer = GetDanmakuServer(roomId);
         if (danmakuServer == null)
         {
             return;
         }
         tcpClient = Connect(danmakuServer);
         StartEventListener(tcpClient);
         StartHeartbeatSender(tcpClient);
         Connected?.Invoke();
     }).Start();
 }
Exemplo n.º 7
0
 private void StartHeartbeatSender()
 {
     StopHeartbeatSender();
     HeartbeatSenderThread = new Thread(delegate()
     {
         IsHeartbeatSenderRunning = true;
         while (IsHeartbeatSenderRunning)
         {
             try
             {
                 PackWriter.SendMessage((int)BiliPackWriter.MessageType.HEARTBEAT, "[object Object]");
             }
             catch (SocketException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             catch (InvalidOperationException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             catch (IOException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             Thread.Sleep(30 * 1000);
         }
     });
     HeartbeatSenderThread.Start();
 }
Exemplo n.º 8
0
        /// <summary>
        /// Restores session or tries to establish a new one.
        /// Invokes <see cref="ConnectionSucceed"/> or <see cref="ConnectionFailed"/>.
        /// </summary>
        /// <returns></returns>
        public async Task <AuthenticationResponse> ConnectAsync(string username = null)
        {
            var response = await RestoreTokenAsync(username);

            switch (response)
            {
            case AuthenticationResponse.Authenticated:
            case AuthenticationResponse.UserInfoUpdated:
                ConnectionSucceed?.Invoke();
                break;

            case AuthenticationResponse.NewAccountCreated:
                NewAccountCreated?.Invoke();
                ConnectionSucceed?.Invoke();
                break;

            case AuthenticationResponse.ErrorUsernameAlreadyExists:
            case AuthenticationResponse.ErrorInternal:
                ConnectionFailed?.Invoke();
                break;

            default:
                Debug.LogError("Unhandled response received: " + response);
                break;
            }

            return(response);
        }
Exemplo n.º 9
0
        private DanmakuServer GetDanmakuServer(long roomId)
        {
            roomId = GetRealRoomId(roomId);
            if (roomId < 0)
            {
                return(null);
            }
            try
            {
                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create("https://api.live.bilibili.com/room/v1/Danmu/getConf?room_id=" + roomId);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Json.Value      json     = Json.Parser.Parse(response.GetResponseStream());
                if (json["code"] != 0)
                {
                    Console.Error.WriteLine("Error occurs when resolving dm servers");
                    Console.Error.WriteLine(json.ToString());
                    return(null);
                }

                DanmakuServer danmakuServer = new DanmakuServer();
                danmakuServer.RoomId  = roomId;
                danmakuServer.Server  = json["data"]["host_server_list"][0]["host"];
                danmakuServer.Port    = json["data"]["host_server_list"][0]["port"];
                danmakuServer.WsPort  = json["data"]["host_server_list"][0]["ws_port"];
                danmakuServer.WssPort = json["data"]["host_server_list"][0]["wss_port"];
                danmakuServer.Token   = json["data"]["token"];

                return(danmakuServer);
            }
            catch (WebException)
            {
                ConnectionFailed?.Invoke("直播间信息获取失败");
                return(null);
            }
        }
Exemplo n.º 10
0
        public ClientWorld(ClientOptions options) : base(options, new ClientWorldCreator(options))
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));

            Connected    += i => NetworkId = i;
            Disconnected += () => NetworkId = 0;

            void OnWorldCreate()
            {
                HookSystem hookSystem = World.GetHookSystem();

                hookSystem.RegisterHook <DisconnectedEvent>(e => Disconnected?.Invoke());
                hookSystem.RegisterHook <ConnectionInitiatedEvent>(e => Connecting?.Invoke());
                hookSystem.RegisterHook <ConnectionCompleteEvent>(e =>
                {
                    Connected?.Invoke(World.EntityManager
                                      .GetComponentData <NetworkIdComponent>(
                                          World.GetExistingSystem <CreateRpcRequestSystem>().CommandTargetComponentEntity)
                                      .Value);
                });
                hookSystem.RegisterHook <ConnectionFailedEvent>(e =>
                                                                ConnectionFailed?.Invoke(((ConnectionFailedEvent)e).Message.ToString()));
            }

            if (WorldCreator.WorldIsCreated)
            {
                OnWorldCreate();
            }

            WorldCreated += OnWorldCreate;
        }
Exemplo n.º 11
0
        public async Task ConnectAsync()
        {
            try
            {
                IsBusy = true;

                string negotiateJson = await client.GetStringAsync($"{Constants.HostName}/api/negotiate");

                NegotiateInfo negotiate = JsonConvert.DeserializeObject <NegotiateInfo>(negotiateJson);

                HubConnection connection = new HubConnectionBuilder()
                                           .AddNewtonsoftJsonProtocol()
                                           .WithUrl(negotiate.Url, options =>
                {
                    options.AccessTokenProvider = async() => negotiate.AccessToken;
                })
                                           .Build();

                connection.Closed += Connection_Closed;
                // The ConnectAsync method registers an event handler for the message name defined in the sample application's Constants.cs file, which is "newMessage" by default.
                connection.On <JObject>(Constants.MessageName, AddNewMessage);
                await connection.StartAsync();

                IsConnected = true;
                IsBusy      = false;

                Connected?.Invoke(this, true, "Connection successful.");
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, false, ex.Message);
                IsConnected = false;
                IsBusy      = false;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initialize a new login.
        /// </summary>
        /// <returns>Successful</returns>
        public bool Init()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://passport.bilibili.com/qrcode/getLoginUrl");
                string         result;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                        using (StreamReader reader = new StreamReader(stream))
                            result = reader.ReadToEnd();


                Json.Value getLoginUrl = Json.Parser.Parse(result);
                LoginUrlRecieved?.Invoke(this, getLoginUrl["data"]["url"]);
                Bitmap qrBitmap = RenderQrCode(getLoginUrl["data"]["url"]);
                QRImageLoaded?.Invoke(this, qrBitmap);
                oauthKey = getLoginUrl["data"]["oauthKey"];
                return(true);
            }
            catch (WebException ex)
            {
                ConnectionFailed?.Invoke(this, ex);
                return(false);
            }
        }
Exemplo n.º 13
0
 private void StartHeartbeatSender(TcpClient tcpClient)
 {
     StopHeartbeatSender();
     heartbeatSenderThread = new Thread(delegate()
     {
         heartbeatSenderStarted = true;
         while (heartbeatSenderStarted)
         {
             try
             {
                 BiliPackWriter.SendMessage(tcpClient.GetStream(), (int)BiliPackWriter.MessageType.HEARTBEAT, "");
             }
             catch (SocketException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             catch (InvalidOperationException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             catch (IOException)
             {
                 ConnectionFailed?.Invoke("心跳包发送失败");
                 Disconnect();
             }
             Thread.Sleep(30 * 1000);
         }
     });
     heartbeatSenderThread.Start();
 }
Exemplo n.º 14
0
        public void Connect(string hostname, int port)
        {
            if (string.IsNullOrEmpty(hostname) || port < 1)
            {
                return;
            }

            if (!IPAddress.TryParse(hostname, out IPAddress ip))
            {
                ip = Dns.GetHostAddresses(hostname)[0];
            }
            if (ip == null)
            {
                throw new Exception("Could not resolve hostname \"" + hostname + "\"");
            }

            _socket.BeginConnect(ip.ToString(), port, ar => {
                try {
                    _socket.EndConnect(ar);

                    if ((( TcpSocket )ar.AsyncState)._socket.Connected)
                    {
                        ConnectionSuccessful?.Invoke(this);
                    }
                    else
                    {
                        ConnectionFailed?.Invoke(this, null);
                    }
                } catch (Exception ex) {
                    ConnectionFailed?.Invoke(this, ex);
                }
            }, this);
        }
Exemplo n.º 15
0
        public void Start(string pin, string playerName)
        {
            Start();
            RunNetworkerTask(() => _networker.Start());

            Pin        = pin;
            PlayerName = playerName;

            // Request discovery
            NetDataWriter writer = new NetDataWriter();

            writer.Put(pin);
            RunNetworkerTask(() => _networker.SendDiscoveryRequest(writer, NetConstants.PORT));

            // Stop on timeout
            Task.Run(() =>
            {
                Task.Delay(DISCOVERY_TIMEOUT).Wait();
                if (!IsConnected && IsRunning)
                {
                    Log.Information("Client failed to connect to server");
                    Stop();
                    ConnectionFailed?.Invoke(this, EventArgs.Empty);
                }
            });

            Log.Information("Client started");
            Log.Information("Client attempting to discover server with pin {pin}", Pin);
        }
Exemplo n.º 16
0
        private void WaitingGreating(ICancelable greatingMessageTimer)
        {
            Receive <Tcp.Received>(data =>
            {
                _lastDataReceived = DateTime.Now;
                greatingMessageTimer.Cancel();
                _greatingResponse = GreatingResponse.Parse(data.Data.ToArray());
                var scheduler     = Context.System.Scheduler;
                var self          = Self;
                Self.Ask <Response>(Request.Ping().Build(), _heartbeatDelay).ContinueWith(t =>
                {
                    StateChange state = new Connected(_host.ToString(), _port, _greatingResponse.Salt, _greatingResponse.Version);
                    if (t.IsFaulted)
                    {
                        state = new ConnectionFailed(_host.ToString(), _port);
                    }
                    else
                    {
                        _heartbeatTimer = scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(1), self, new Heartbeat(_heartbeatDelay), self);
                    }


                    return(state);
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously).PipeTo(_listener);
                Become(WaitingAuth);
            });

            Receive <ReceiveTimeout>(t =>
            {
                _currentConnection.Socket.Tell(Tcp.Close.Instance);
            });

            ConnectionManagement();
        }
Exemplo n.º 17
0
        public async Task <string> GetAsync(string url, bool cache = false, Dictionary <string, string> headers = null)
        {
            try
            {
                url += LangIgnoreParam(url);
                //if (!NetworkInterface.GetIsNetworkAvailable())
                //throw new NoInternetConnection();
                //TryAddAuth();
                var msg = new HttpRequestMessage(HttpMethod.Get, url);
                msg.Headers.IfModifiedSince = DateTimeOffset.Now;
                if (headers != null)
                {
                    foreach (var h in headers)
                    {
                        msg.Headers.TryAddWithoutValidation(h.Key, h.Value);
                    }
                }
                var response = await _httpClient.SendAsync(msg, _cts.Token);

                var content = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();
                return(content);
            }
            catch (Exception e)
            {
                ConnectionFailed?.Invoke(e, EventArgs.Empty);
                return(null);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initialize a new login.
        /// </summary>
        /// <returns>Successful</returns>
        public bool Init()
        {
            try
            {
                HttpWebRequest  request    = (HttpWebRequest)WebRequest.Create("https://passport.bilibili.com/qrcode/getLoginUrl");
                HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
                Stream          dataStream = response.GetResponseStream();
                StreamReader    reader     = new StreamReader(dataStream);
                string          result     = reader.ReadToEnd();
                reader.Close();
                response.Close();
                dataStream.Close();

                IJson getLoginUrl = JsonParser.Parse(result);
                LoginUrlRecieved?.Invoke(this, getLoginUrl.GetValue("data").GetValue("url").ToString());
                Bitmap qrBitmap = RenderQrCode(getLoginUrl.GetValue("data").GetValue("url").ToString());
                QRImageLoaded?.Invoke(this, qrBitmap);
                oauthKey = getLoginUrl.GetValue("data").GetValue("oauthKey").ToString();
                return(true);
            }
            catch (WebException ex)
            {
                ConnectionFailed?.Invoke(this, ex);
                return(false);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Restores session or tries to establish a new one.
        /// Invokes <see cref="ConnectionSucceed"/> or <see cref="ConnectionFailed"/>.
        /// </summary>
        /// <returns></returns>
        public async Task <(bool success, string message)> ConnectAsync(string email,
                                                                        string password,
                                                                        bool create = false,
                                                                        string ip   = "localhost",
                                                                        int p       = 7350)
        {
            ipAddress = ip;
            port      = p;
            try
            {
                session = await client.AuthenticateEmailAsync(email, password, create : create);

                account = await GetAccountAsync();
            }
            catch (ApiResponseException ex)
            {
                ConnectionFailed?.Invoke();
                return(false, ex.Message);
            }

            Debug.LogFormat("New user: {0}, {1}", session.Created, session);
            ConnectionSucceed?.Invoke();
            if (session.Created)
            {
                NewAccountCreated?.Invoke();
            }

            return(true, session.Created ? "Account created, connecting ..." : "Connecting");
        }
        public async Task ConnectAsync()
        {
            try
            {
                IsBusy = true;

                string negotiateJson = await client.GetStringAsync($"{Constants.HostName}/api/negotiate");

                NegotiateInfo negotiate = JsonConvert.DeserializeObject <NegotiateInfo>(negotiateJson);

                HubConnection connection = new HubConnectionBuilder()
                                           .AddNewtonsoftJsonProtocol()
                                           .WithUrl(negotiate.Url, options =>
                {
                    options.AccessTokenProvider = async() => negotiate.AccessToken;
                })
                                           .Build();

                connection.Closed += Connection_Closed;
                connection.On <JObject>(Constants.MessageName, AddNewMessage);
                await connection.StartAsync();

                IsConnected = true;
                IsBusy      = false;

                Connected?.Invoke(this, true, "Connection successful.");
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, false, ex.Message);
                IsConnected = false;
                IsBusy      = false;
            }
        }
 Task Connection_Closed(Exception arg)
 {
     ConnectionFailed?.Invoke(this, false, arg.Message);
     IsConnected = false;
     IsBusy      = false;
     return(Task.CompletedTask);
 }
Exemplo n.º 22
0
        private void Setup()
        {
            try
            {
                _client = new TcpClient(_server, _port);
                _stream = _client.GetStream();

                _reader = new BinaryReader(_stream);
                _writer = new BinaryWriter(_stream);

                int result = _reader.ReadByte();
                if (result == MessageDictionary.Hello)
                {
                    _writer.Write(MessageDictionary.Hello);
                    _writer.Write(MessageDictionary.ImUploadClient);
                    _writer.Write(_userId);

                    if (_reader.Read() == MessageDictionary.OK)
                    {
                        _isConnected = true;

                        ConnectionSuccess?.Invoke(this, EventArgs.Empty);
                    }
                }
                else
                {
                    _isConnected = false;
                    ConnectionFailed?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, EventArgs.Empty);
            }
        }
Exemplo n.º 23
0
        public async Task ConnectAsync(string authToken)
        {
            try
            {
                IsBusy = true;
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {authToken}");
                string negotiateJson = await client.GetStringAsync($"{hostName}/api/negotiate");

                NegotiateInfo negotiate  = JsonConvert.DeserializeObject <NegotiateInfo>(negotiateJson);
                HubConnection connection = new HubConnectionBuilder()
                                           .WithUrl(negotiate.Url, options =>
                {
                    options.AccessTokenProvider = async() => negotiate.AccessToken;
                })
                                           .Build();
                connection.Closed += Connection_Closed;
                connection.On <JObject>(methodName, AddNewMessage);
                await connection.StartAsync();

                IsConnected = true;
                IsBusy      = false;

                Connected?.Invoke(this, true, "Connection successful.");
            }
            catch (Exception ex)
            {
                ConnectionFailed?.Invoke(this, false, ex.Message);
                IsConnected = false;
                IsBusy      = false;
            }
        }
Exemplo n.º 24
0
        private bool InitConnection(DanmakuServer danmakuServer)
        {
            Json.Value initMsg = new Json.Value.Object
            {
                ["uid"]       = 0,
                ["roomid"]    = danmakuServer.RoomId,
                ["protover"]  = 2,
                ["platform"]  = "web",
                ["clientver"] = "1.12.0",
                ["type"]      = 2,
                ["key"]       = danmakuServer.Token
            };

            try
            {
                PackWriter.SendMessage((int)BiliPackWriter.MessageType.CONNECT, initMsg.ToString());
                return(true);
            }
            catch (SocketException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
            catch (InvalidOperationException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
            catch (IOException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
        }
Exemplo n.º 25
0
        public async Task ConnectAsync()
        {
            if (IsConnected)
            {
                return;
            }

            try
            {
                Connecting?.Invoke(this, new ConnectionEventArgs($"Try to Connect to SignalR Hub"));

                await _hubConnection.StartAsync().ConfigureAwait(false);

                if (!IsConnected)
                {
                    throw new InvalidOperationException($"Connecting to SignalR Hub failed.");
                }

                Connected?.Invoke(this, new ConnectionEventArgs($"Successfully Connected to SignarR Hub. ConnectionId:{_hubConnection.ConnectionId}"));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                ConnectionFailed?.Invoke(this, new ConnectionEventArgs(ex.Message));
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Attemts to connect to the specified server with the specified
        /// name and ID. Cancels any ongoing connection or connection attempt.
        /// </summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <param name="info"></param>
        public void Connect(IPEndPoint address, ConnectionInfo info)
        {
            //TODO - unsure why but this method would not work properly on linux on whichever thread was calling it
            //running a new task seems to work for now
            Task.Run(() =>
            {
                if (IsConnected)
                {
                    throw new InvalidOperationException("Socket already connected");
                }

                if (AttemptingConnection)
                {
                    tcpSocket.Dispose();
                }

                conInfo = info;

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

                ServerAddress = address;

                if (allowudp)
                {
                    udpC?.Dispose();
                    udpC = new ISUdpClient(ServerAddress);
                    udpC.InputReceived += UdpC_InputReceived;
                }


                AttemptingConnection = true;
                tcpSocket            = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true //Disable nagles algorithm!
                };

                serverResponded = false;
                errorHandled    = false;

                ISLogger.Write("Attempting to connect to {0} as {1}", address, info.Name);

                try
                {
                    tcpSocket.BeginConnect(address, TcpSocket_ConnectCallback, tcpSocket);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    ISLogger.Write("BeginConnect threw " + ex.Message);
                    ConnectionFailed?.Invoke(this, ex.Message);
                    return;
                }

                serverReplyTimer = new Timer(ServerReplyTimerCallback, null, 5000, 0);
            });
        }
Exemplo n.º 27
0
        protected virtual void OnConnectionFailed()
        {
            // DEBUG: Log failed connection.
            Log.Debug($"Connection to ('{_address}:{_port}') failed after ({ConnectionAttempts}) attempt(s).");

            ConnectionState = ClientConnectionState.Disconnected;
            ConnectionFailed?.Invoke(this, new EventArgs());
        }
Exemplo n.º 28
0
 Task Connection_Closed(Exception arg)
 {
     Console.WriteLine("Signal R connection closed.");
     ConnectionFailed?.Invoke(this, false, arg.Message);
     IsConnected = false;
     IsBusy      = false;
     return(Task.CompletedTask);
 }
Exemplo n.º 29
0
 private void HandleClientDeclinedMessage(ClientDeclinedMessage message)
 {
     serverResponded = true;
     ConnectionFailed?.Invoke(this, "The server declined the connection '" + message.Reason + "'");
     errorHandled = true;
     udpC?.Dispose();
     AttemptingConnection = false;
 }
Exemplo n.º 30
0
 private void BiliLoginQR_ConnectionFailed(BiliLoginQR sender, WebException ex)
 {
     Dispatcher.Invoke(new Action(() =>
     {
         QrImageBox.Visibility = Visibility.Hidden;
     }));
     ConnectionFailed?.Invoke(this, ex);
 }