C# Sending multiple objects over same Socket -
i'm trying send multiple different objects (well, same object types, different values) 1 socket another. can send 1 object fine using 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 want send multiple messages (put full client code in loop , not call client.close()) how able determine when full object has been received client? putting client code in loop 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); } // stuff wait new message } the client hang @ _clientreceive.receive(buffer) because doesn't receive close() client , never 0 received bytes. if close connection on server, loop through , error out @ deserialize memorystream instead of blocking @ the_clientreceive.receive(buffer) in anticipation of object being sent.
i hope makes sense. pointers?
you might send header message informs receiving end how many bytes expect. similar content-length directive in http. other option, make custom termination string send @ end (obviously can't appear bit bit anywhere in serialized objects' binary payload, why former solution i'd do).
Comments
Post a Comment