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); } }); }
/// <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); }
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); }
protected override void HandleConnectedFailed(string error) { base.IsConnected = false; errorHandled = true; base.HandleConnectedFailed(error); ConnectionFailed?.Invoke(this, error); }
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); } ); }
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(); }
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); } }
/// <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); }
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); } }
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; }
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; } }
/// <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); } }
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(); }
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); }
/// <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(); }
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); }
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); } }
/// <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); } }
/// <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); }
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); } }
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; } }
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)); } }
/// <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); }); }
private void BiliLoginQR_ConnectionFailed(BiliLoginQR sender, WebException ex) { Dispatcher.Invoke(new Action(() => { QrImageBox.Visibility = Visibility.Hidden; })); ConnectionFailed?.Invoke(this, ex); }
Task Connection_Closed(Exception arg) { Console.WriteLine("Signal R connection closed."); ConnectionFailed?.Invoke(this, false, arg.Message); IsConnected = false; IsBusy = false; return(Task.CompletedTask); }
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()); }
private void HandleClientDeclinedMessage(ClientDeclinedMessage message) { serverResponded = true; ConnectionFailed?.Invoke(this, "The server declined the connection '" + message.Reason + "'"); errorHandled = true; udpC?.Dispose(); AttemptingConnection = false; }
/// <summary> /// Handles and fires the <see cref="OnConnectionFailed(EventArgs)"/> event. /// </summary> internal void OnConnectionFailed(EventArgs e) { ConnectionFailed?.Invoke(this, e); Running = false; Console.WriteLine("Connection lost."); Console.WriteLine("Reconneting..."); OnReconnecting(null); Connect(ConnectionData); }