/// <summary> /// Initializes a new instance of the <see cref="Client"/> class. /// </summary> public Client() { OutgoingPackets = new Queue <Packet>(); Keepalive = new Keepalive(this); OutgoingPacketCooldown = new Stopwatch(); OutgoingPacketCooldown.Restart(); IncomingPacketReceieved = true; }
/// <summary> /// Updates this instance. /// </summary> /// <returns>Task.</returns> public async Task Update() { if (IsConnected) { await ProcessPacketStream(); Keepalive.Update(); } }
/// <summary> /// Processes the packet stream. /// </summary> /// <returns>Task.</returns> private async Task ProcessPacketStream() { try { while (IsConnected && (OutgoingPackets.Count != 0 || TcpClient.Available != 0)) { while (IsConnected && TcpClient.Available != 0) { ReceivedPacket?.Invoke(this, new PacketEventArgs { Packet = await Packet.ReadFromStreamAsync(TcpClientStream) }); IncomingPacketReceieved = true; } if (!IsConnected || !CanSendPacket || OutgoingPackets.Count == 0) { continue; } await OutgoingPackets.Dequeue().WriteToStreamAsync(TcpClientStream); OutgoingPacketCooldown.Restart(); IncomingPacketReceieved = false; //// We've successfully sent or recieved data so the keepalive can be pushed back. Keepalive.Reset(); } } catch { // Lost connection with the server // No handling is necessary here as the TCPClient will set Connected to false. ServerConnectionDropped?.Invoke(this, new ServerConnectionEventArgs { Message = "Connection to the server has been lost.", Status = ServerConnectionStatusEnum.Disconnected, Timestamp = DateTime.Now }); } }
/// <summary> /// Connects the specified hostname. /// </summary> /// <param name="hostname">The hostname.</param> /// <param name="port">The port.</param> /// <returns>Task<System.Boolean>.</returns> public async Task <bool> Connect(string hostname, int port) { ServerConnectionStarting?.Invoke(this, e: new ServerConnectionEventArgs { Message = $"Connecting to {hostname}:{port}...", Status = ServerConnectionStatusEnum.Connecting, Timestamp = DateTime.Now }); try { TcpClient = new TcpClient { NoDelay = true }; await TcpClient.ConnectAsync(hostname, port); } catch { ServerConnectionFailed?.Invoke(this, new ServerConnectionEventArgs { Message = "Failed to connect! Make sure the server is running and that your hostname and port are correct.", Status = ServerConnectionStatusEnum.Disconnected, Timestamp = DateTime.Now }); } if (!IsConnected) { return(false); } TcpClientStream = TcpClient.GetStream(); ServerConnectionSucceeded?.Invoke(this, new ServerConnectionEventArgs { Message = "Successfully connected.", Status = ServerConnectionStatusEnum.Connected, Timestamp = DateTime.Now }); Keepalive.Reset(); return(true); }