In my client/server program, whenever I need to get data from one or the other it requires a buffer to temporarily store the data. The problem is that I don't know how much data I am going to be getting. I could be receiving a few lines of text or a 100mb file.
I've tried:
1. Getting the Length of the NetworkStream.
Not supported. It would be great if it worked! :'(
2. Reading NetworkStream with a StreamReader and getting the length
The length stops at 8 kilobytes.
3. Increasing the size of the buffer as needed
Data became corrupted.
4. Sending the size of the data and then the actual data
The client gets one thing from the server and doesn't receive anything after that.
I'm completely out of ideas now. Can anyone help me with this?
Here's the sending and receiving code for my server with the attempt and number 4 included.
public static object Receive()
{
MemoryStream MS;
BinaryFormatter BF = new BinaryFormatter();
//Receive the size of the data.
int DataSize = 0;
byte[] SizeBuffer = new byte[1024];
int k = Sock.Receive(SizeBuffer);
DataSize = BitConverter.ToInt32(SizeBuffer, 0);
// Set the size of the buffer and get the actual data
List<byte> ReceivedBytes = new List<byte>();
byte[] DataBuffer = new byte[DataSize];
k = Sock.Receive(DataBuffer);
for (int i = 0; i < k; i++)
{
ReceivedBytes.Add(DataBuffer[i]);
}
MS = new MemoryStream(ReceivedBytes.ToArray());
return BF.Deserialize(MS);
}
public static void Send(object Data)
{
MemoryStream MS = new MemoryStream();
BinaryFormatter BF = new BinaryFormatter();
BF.Serialize(MS, Data);
Sock.Send(BitConverter.GetBytes(MS.ToArray().Length)); //send the length
Sock.Send(MS.ToArray()); // and then the data
}
And this is the send and receive code for the client. Almost identical the server code.
public object Receive()
{
MemoryStream MS;
BinaryFormatter BF = new BinaryFormatter();
//Receive the size of the data.
int DataSize = 0;
byte[] SizeBuffer = new byte[1024];
int k = NetStream.Read(SizeBuffer, 0, SizeBuffer.Length);
DataSize = BitConverter.ToInt32(SizeBuffer, 0);
// Set the size of the buffer and get the actual data
List<byte> ReceivedBytes = new List<byte>();
byte[] DataBuffer = new byte[DataSize];
k = NetStream.Read(DataBuffer, 0, DataBuffer.Length);
for (int i = 0; i < k; i++)
{
ReceivedBytes.Add(DataBuffer[i]);
}
MS = new MemoryStream(ReceivedBytes.ToArray());
return BF.Deserialize(MS);
}
public void Send(object Data)
{
MemoryStream MS = new MemoryStream();
BinaryFormatter BF = new BinaryFormatter();
BF.Serialize(MS, Data);
byte[] LengthOfDataAsBytes = BitConverter.GetBytes(MS.ToArray().Length);
NetStream.Write(LengthOfDataAsBytes, 0, LengthOfDataAsBytes.Length); //Write the length
NetStream.Write(MS.ToArray(), 0, MS.ToArray().Length); //and then the data
}
Absolutely any help is appreciated.