c# - TCP server is not reading fixed size messages correctly -


i'm sending sensor data android device tcp server in c#. android client sends data in fixed size chunks of 32 bytes.

in server read data expecting come in full packs, since tcp stream protocol messages arrive @ server split in 2 parts. know because can watch software called socketsniff.

the problem don't know how handle on server.

all examples found use networkstream.read(), in method have pass array of bytes store data read, offset , number of bytes read. array of bytes must have know size, in case 32.

i don't know real size of message arrived on server, 1 of following situations.

  • if received data size 32 bytes, it's ok.

  • if received data size if greater 32 bytes, think i'm loosing data.

  • if received data size less 32 bytes, lets 20 bytes, these bytes stored in array , last 12 bytes of array remain value of zero. since may receiving zeros there's no way know size received, can't merge remaining data should come in next reading.

my code handles receiving following:

    int buffer = 32;     ...     private void handleclientcomm(object client)     {         tcpclient tcpclient = (tcpclient)client;         networkstream clientstream = tcpclient.getstream();          byte[] message = new byte[buffer];         int bytesread;          while (true)         {             bytesread = 0;              try             {                 bytesread = clientstream.read(message, 0, message.length);             }             catch             {                 break;             }              if (bytesread == 0)             {                 // connection closed                 break;             }              sensordata sensordata = processtcppacket(message);         }         tcpclient.close();     } 

is there way know size of data i'm receiving in socket?

well, yes, have bytesread variable - holds number of bytes read stream. read @ message.length bytes, may read less.

note if there more bytes available, not lose them reading message.length bytes. rather, available next time read stream.

what need add while loop liked this:

int messageread = 0;  while(messageread < message.length) {      int bytesread = clientstream.read(message, messageread, message.length - messageread);     messageread += bytesread;     if(bytesread==0)         return;   // socket closed } // here have full message 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -