55 lines
2.0 KiB
C#
55 lines
2.0 KiB
C#
using System;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Mistox.Server {
|
|
public class TCPConnection : IDisposable {
|
|
|
|
TcpClient _client;
|
|
MistoxServer _instance;
|
|
string _connectionID;
|
|
|
|
public TCPConnection( TcpClient tcpClient, MistoxServer ServerInstance, string ConnectionID ) {
|
|
_client = tcpClient;
|
|
_instance = ServerInstance;
|
|
_connectionID = ConnectionID;
|
|
_client.NoDelay = true;
|
|
|
|
// Start the receive thread
|
|
Thread receiveThread = new Thread(async () => await ReceiveThread() );
|
|
receiveThread.Start();
|
|
}
|
|
|
|
public async Task ReceiveThread() {
|
|
while( _client.Connected && _instance.Connections[_connectionID].Connected ) {
|
|
try {
|
|
_instance.Connections[_connectionID].LastHeartbeat = DateTime.UtcNow;
|
|
byte[] StreamData = new byte[1024];
|
|
int bytesRead = await _client.GetStream().ReadAsync(StreamData, 0, StreamData.Length);
|
|
if( bytesRead > 0 ) {
|
|
dynamic data = mSerialize.tReceive( StreamData.Sub( 0, bytesRead ) );
|
|
if( data != null ) {
|
|
_instance.onReceived?.Invoke( data, new EventArgs() );
|
|
}
|
|
}
|
|
} catch( Exception ) {
|
|
Console.WriteLine( "User disconnected" );
|
|
Dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task Send<T>( T packet ) {
|
|
byte[] byteData = DataPacket.Serialize( packet );
|
|
await _client.GetStream().WriteAsync( byteData, 0, byteData.Length );
|
|
}
|
|
|
|
public void Dispose() {
|
|
_instance.Connections[_connectionID].Connected = false;
|
|
_instance.onUserDisconnected?.Invoke( _instance.Connections[_connectionID], new EventArgs() );
|
|
_instance.Connections.TryRemove( _connectionID, out _ );
|
|
}
|
|
}
|
|
}
|