mirror of
https://github.com/besterprotocol/besterd
synced 2023-12-13 21:00:32 +01:00
Read in preamble (4 bytes) and handle errors
This commit is contained in:
parent
79851163c6
commit
03cfc0e277
|
@ -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);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue