using System; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace Mistox.Server { public class TCPConnection : IDisposable { TcpClient _client; TcpClientConnection _connection; public TCPConnection( TcpClient tcpClient, string ConnectionID ) { _client = tcpClient; _client.NoDelay = true; _connection = ServerInterface.Connections[ConnectionID]; ServerInterface.ServerInstance.InvokeUserConnected( ServerInterface.Connections[ConnectionID] ); // Start the receive thread Thread receiveThread = new Thread(async () => await ReceiveThread() ); receiveThread.Start(); } public async Task ReceiveThread() { while( _client.Connected && _connection.Connected && ServerInterface.ServerInstance.Alive ) { try { _connection.LastHeartbeat = DateTime.UtcNow; byte[] StreamData = new byte[1024]; int bytesRead = await _client.GetStream().ReadAsync(StreamData, 0, StreamData.Length); if( bytesRead > 0 ) { dynamic data = Serializer.tReceive( StreamData.Sub( 0, bytesRead ) ); if( data != null ) { ServerInterface.ServerInstance.InvokeDataReceived( data ); } } } catch( Exception ) { Console.WriteLine( "User disconnected" ); Dispose(); } } } public async Task Send( T packet ) { byte[] byteData = DataPacket.Serialize( packet ); await _client.GetStream().WriteAsync( byteData, 0, byteData.Length ); } public void Dispose() { _connection.Connected = false; ServerInterface.ServerInstance.InvokeUserDisconnected( _connection ); ServerInterface.ServerInstance.Alive = false; ServerInterface.Connections.TryRemove( _connection.UserName, out _ ); } } }