Rework the server connection to be more structured
This commit is contained in:
1 parent
7b58ca0338
commit
64dbd02874
10 files changed
+139
-141
No files matched your search
@@ -0,0 +1,54 @@
|
||||
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 _ );
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user