public static object Recieve(NetworkStream stream)
{
int dataLength;
byte[] data = new byte[sizeof(Int32)];
int bytesRead = 0;
int totalBytesRead = 0;
try {
// Read the length integer
do {
bytesRead = stream.Read(data, totalBytesRead, (data.Length - totalBytesRead));
totalBytesRead += bytesRead;
} while (totalBytesRead < sizeof(Int32) && bytesRead != 0);
if (totalBytesRead < sizeof(Int32)) {
if (totalBytesRead != 0) Console.Error.WriteLine("Message Recieve Failed: connection closed unexpectedly");
return null;
}
if (BitConverter.IsLittleEndian) Array.Reverse(data);
dataLength = BitConverter.ToInt32(data, 0);
if (dataLength == 0) {
// A test message was sent.
return "Test";
} else {
data = new byte[dataLength];
// Read data until the client disconnects
totalBytesRead = 0;
do {
bytesRead = stream.Read(data, totalBytesRead, (dataLength - totalBytesRead));
totalBytesRead += bytesRead;
} while (totalBytesRead < dataLength && bytesRead != 0);
if (totalBytesRead < dataLength) {
Console.Error.WriteLine("Message Receive Failed: connection closed unexpectedly");
return null;
}
return Unpack(data);
}
} catch (Exception e) {
Console.Error.WriteLine("A socket error has occured: " + e.ToString());
return null;
}
}