1 module bmessage;
2 
3 import std.socket : Socket, SocketFlags, MSG_WAITALL;
4 
5 public bool receiveMessage(Socket originator, ref byte[] receiveMessage)
6 {
7 	/* Construct a buffer to receive into */
8 	byte[] receiveBuffer;
9 
10 	/* Read 4 bytes of length */
11 	receiveBuffer.length = 4;
12 	originator.receive(receiveBuffer, cast(SocketFlags)MSG_WAITALL);
13 
14 	/* Response message length */
15 	int messageLength;
16 	// writeln("Message length is: ", cast(uint)messageLength);
17 
18 	/* Little endian version you simply read if off the bone (it's already in the correct order) */
19 	version(LittleEndian)
20 	{
21 		messageLength = *cast(int*)receiveBuffer.ptr;
22 	}
23 
24 	/* Big endian requires we byte-sapped the little-endian encoded number */
25 	version(BigEndian)
26 	{
27 		byte[] swappedLength;
28 		swappedLength.length = 4;
29 
30 		swappedLength[0] = receiveBuffer[3];
31 		swappedLength[1] = receiveBuffer[2];
32 		swappedLength[2] = receiveBuffer[1];
33 		swappedLength[3] = receiveBuffer[0];
34 
35 		messageLength = *cast(int*)swappedLength.ptr;
36 	}
37 
38 	/* Reset buffer */
39 	receiveBuffer.length = cast(uint)messageLength;
40 
41 	/* Read the full message */
42 	originator.receive(receiveBuffer, cast(SocketFlags)MSG_WAITALL);
43 
44 	// writeln("Message ", fullMessage);
45 
46 	return true;
47 }
48 
49 public bool sendMessage(Socket recipient, byte[] message)
50 {
51 	/* The message buffer */
52 	byte[] messageBuffer;
53 
54 	/* Encode the 4 byte message length header (little endian) */
55 	int payloadLength = cast(int)message.length;
56 	byte* lengthBytes = cast(byte*)&payloadLength;
57 
58 	/* On little endian simply get the bytes as is (it would be encoded as little endian) */
59 	version(LittleEndian)
60 	{
61 		messageBuffer ~= *(lengthBytes+0);
62 		messageBuffer ~= *(lengthBytes+1);
63 		messageBuffer ~= *(lengthBytes+2);
64 		messageBuffer ~= *(lengthBytes+3);
65 	}
66 
67 	/* On Big Endian you must swap the big-endian-encoded number to be in little endian ordering */
68 	version(BigEndian)
69 	{
70 		messageBuffer ~= *(lengthBytes+3);
71 		messageBuffer ~= *(lengthBytes+2);
72 		messageBuffer ~= *(lengthBytes+1);
73 		messageBuffer ~= *(lengthBytes+0);
74 	}
75 	
76 
77 	/* Add the message to the buffer */
78 	messageBuffer ~= cast(byte[])message;
79 
80 	/* Send the message */
81 	long bytesSent = recipient.send(messageBuffer);
82 
83 	/* TODO: Compact this */
84 	return bytesSent > 0;
85 }