I'm trying to send multiple different objects (well, they are the same object types, just with different values) from one socket to another. I can send one object just fine using the following code:
Client:
var buffer = new byte[1024];
var binFormatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
int bytesRead;
while ((bytesRead = _clientReceive.Receive(buffer)) > 0);
{
ms.Write(buffer, 0, bytesRead);
}
ms.Position = 0;
message = (Message)binFormatter.Deserialize(ms);
}
server:
var gm = new Message { Message = "ObjectType", Object = Data };
using (var mem = new MemoryStream())
{
var binFormatter = new BinaryFormatter();
binFormatter.Serialize(mem, gm);
var gmData = mem.ToArray();
client.Send(gmData, gmData.Length, SocketFlags.None);
client.Close();
}
but if I want to send multiple messages (put the full client code in a loop and not call client.Close()
) how would I be able to determine when the full object has been received by the client? Putting the client code in a loop like this:
while (_isReceivingStarted)
{
var buffer = new byte[1024];
var binFormatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
int bytesRead;
while ((bytesRead = _clientReceive.Receive(buffer)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
ms.Position = 0;
message = (Message) binFormatter.Deserialize(ms);
}
// Do stuff then wait for new message
}
the client will hang at _clientReceive.Receive(buffer)
because it doesn't receive the Close() from the client and never get the 0 received bytes. If I close the connection on the server, it will loop through and then error out at the Deserialize MemoryStream instead of blocking at the_clientReceive.Receive(buffer)
in anticipation of another object being sent.
I hope this makes sense. Any pointers?