1
0
Fork 0
mirror of https://github.com/besterprotocol/bformat synced 2023-12-13 21:30:24 +01:00
- Holds teh socket for the lifetime of usage and you can now use `receiveMessage(ref byte[])` and `sendMesssage(byte[])` on it
This commit is contained in:
Tristan B. Velloza Kildaire 2023-04-30 00:01:23 +02:00
parent f347229d27
commit b9c4b37b59
2 changed files with 123 additions and 101 deletions

View file

@ -7,7 +7,7 @@ module bformat;
* Encodes the provided message into the bformat format
* and sends it over the provided socket
*/
public import bformat.sockets : sendMessage;
public import bformat.sockets : BClient;
/**
* Receives a message from the provided socket
@ -15,7 +15,7 @@ public import bformat.sockets : sendMessage;
* and finally placing the resulting payload in
* the provided array
*/
public import bformat.sockets : receiveMessage;
// public import bformat.sockets : receiveMessage;
/**
* Encodes the provided message into the bformat format

View file

@ -5,6 +5,19 @@ module bformat.sockets;
import std.socket : Socket, SocketFlags, MSG_WAITALL;
public class BClient
{
/**
* Underlying socket
*/
private Socket socket;
// TODO: comment
this(Socket socket)
{
this.socket = socket;
}
/**
* Receives a message from the provided socket
* by decoding the streamed bytes into bformat
@ -17,7 +30,7 @@ import std.socket : Socket, SocketFlags, MSG_WAITALL;
*
* Returns: true if the receive succeeded, false otheriwse
*/
public bool receiveMessage(Socket originator, ref byte[] receiveMessage)
public bool receiveMessage(ref byte[] receiveMessage)
{
/* Construct a buffer to receive into */
byte[] receiveBuffer;
@ -30,7 +43,7 @@ public bool receiveMessage(Socket originator, ref byte[] receiveMessage)
/* Get the length of the message */
byte[4] messageLengthBytes;
bytesReceived = originator.receive(messageLengthBytes, cast(SocketFlags)MSG_WAITALL);
bytesReceived = socket.receive(messageLengthBytes, cast(SocketFlags)MSG_WAITALL);
/* If there was an error reading from the socket */
if(!(bytesReceived > 0))
@ -66,7 +79,7 @@ public bool receiveMessage(Socket originator, ref byte[] receiveMessage)
/* Read the full message */
receiveBuffer.length = messageLength;
bytesReceived = originator.receive(receiveBuffer, cast(SocketFlags)MSG_WAITALL);
bytesReceived = socket.receive(receiveBuffer, cast(SocketFlags)MSG_WAITALL);
/* If there was an error reading from the socket */
if(!(bytesReceived > 0))
@ -93,7 +106,7 @@ public bool receiveMessage(Socket originator, ref byte[] receiveMessage)
*
* Returns: true if the send succeeded, false otherwise
*/
public bool sendMessage(Socket recipient, byte[] message)
public bool sendMessage(byte[] message)
{
/* The message buffer */
byte[] messageBuffer;
@ -125,8 +138,17 @@ public bool sendMessage(Socket recipient, byte[] message)
messageBuffer ~= cast(byte[])message;
/* Send the message */
long bytesSent = recipient.send(messageBuffer);
long bytesSent = socket.send(messageBuffer);
/* TODO: Compact this */
return bytesSent > 0;
}
}