Files
GameServer/MistoxServer/Server/TCPConnection.cs
T
2026-07-02 21:48:43 -07:00

53 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;
string _connectionID;
public TCPConnection( TcpClient tcpClient, string ConnectionID ) {
_client = tcpClient;
_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 && ServerInterface.Connections[_connectionID].Connected ) {
try {
ServerInterface.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 ) {
ServerInterface.ServerInstance.InvokeOnReceived( data );
}
}
} 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() {
ServerInterface.Connections[_connectionID].Connected = false;
ServerInterface.ServerInstance.InvokeOnUserDisconnected( ServerInterface.Connections[_connectionID] );
ServerInterface.Connections.TryRemove( _connectionID, out _ );
}
}
}