From 03cfc0e27737b140a2f394734323ab8b0c4d203e Mon Sep 17 00:00:00 2001 From: "Tristan B. Kildaire" Date: Thu, 16 Apr 2020 17:50:10 +0200 Subject: [PATCH] Read in preamble (4 bytes) and handle errors --- source/server/types.d | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/source/server/types.d b/source/server/types.d index ed59183..6a371cc 100644 --- a/source/server/types.d +++ b/source/server/types.d @@ -2,8 +2,9 @@ module server.types; import utils.debugging : debugPrint; import std.conv : to; -import std.socket : Socket, AddressFamily, SocketType, ProtocolType, parseAddress; +import std.socket : Socket, AddressFamily, SocketType, ProtocolType, parseAddress, SocketFlags; import core.thread : Thread; +import std.stdio : writeln; public class BesterServer { @@ -34,7 +35,9 @@ public class BesterServer /* Wait for an incoming connection */ Socket clientConnection = serverSocket.accept(); - /* TODO: Spawn new BesterConnection object here */ + /* Create a new client connection handler and start its thread */ + BesterConnection besterConnection = new BesterConnection(clientConnection); + besterConnection.start(); } } @@ -48,17 +51,45 @@ private class BesterConnection : Thread this(Socket clientConnection) { - /* TODO */ /* Save socket and set thread worker function pointer */ super(&run); + this.clientConnection = clientConnection; + + debugPrint("New client handler spawned for " ~ clientConnection.remoteAddress().toAddrString()); } /* Read/send loop */ private void run() { + /* Receive buffer */ + byte[] buffer; + while(true) { + /* Make the dynamic array's size 4 */ + buffer.length = 4; + + /* Peek for the first 4 bytes (retrieve message size) */ + long bytesReceived = clientConnection.receive(buffer, SocketFlags.PEEK); + writeln(cast(ulong)bytesReceived); + + /* Make sure exactly 4 bytes were received */ + if (bytesReceived != 4) + { + /* If we don't get exactly 4 bytes, drop the client */ + debugPrint("Did not get exactly 4 bytes for preamble, disconnecting client..."); + clientConnection.close(); + break; + } + + /* Get the message length */ + int messageLength = *(cast(int*)buffer.ptr); + + /* Receive the whole message in its entirety */ + buffer.length = messageLength; + bytesReceived = clientConnection.receive(buffer); + } }