c# - NetworkStream class: Read Issue -


i making server client program in core c#./net in send data serialised 1 client server there 2 exceptions occur when data large. works fine throws exception. ioexception or serialisation exception thrown.

here code receive , deserialise data:

memorystream mst = new memorystream(); strread.readtimeout = 250;  try {     int b = strread.read(outstream, 0, outstream.length);     while (b > 0)     {         console.writeline("recieving data " + b);         mst.write(outstream, 0, b);         try         {             b = strread.read(outstream, 0, outstream.length);         }         catch (ioexception ioex)         {             console.writeline(ioex.targetsite);             b = 0;         }     }     console.writeline("size of recieved bytes " + b); } catch (exception except) {     console.writeline(except.stacktrace + "\r\n" + except.targetsite); }  //int bcount = strread.read(outstream, 0, outstream.length);  mst.read(outstream, 0, outstream.length); m = (message)deserialize(outstream); 

deserialization method:

public message deserialize(byte[] v) {     iformatter formatter = new binaryformatter();     memorystream mem = new memorystream();     message mydat = null;     try     {         mem.write(v, 0, v.length);         mem.seek(0, 0);         mydat = (message)formatter.deserialize(mem);     }     catch (serializationexception ex)     {         console.writeline("salman deserialization " + ex.message);     }         {         mem.flush();         mem.close();     }      return mydat; } 

analysis

it seems receiver not have notion of "message boundary".

the receiver accumulates received data using instance of memorystream class until remote host shuts down connection: while (b > 0). so, if multiple messages sent sender , after connection closed sender, receiver completes receiving accumulation having both messages stored in instance of memorystream class. after there attempt interpret accumulated data follows:

mst.read(outstream, 0, outstream.length); m = (message)deserialize(outstream); 

possible problems such interpretation:

  • what if single message has not been received? — failed deserialize.
  • what if multiple messages have been received? — failed deserialize.
  • etc.

solution

the message boundary concept must introduced extract ("separate") messages network stream (tcp-stream). can done either using fixed-size message header or message terminator.

please refer article: tcp/ip client-server application: exchange string messages.

hope helps!


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -