byte - Help needed with reading data from server in java -


i having bit of trouble datainputstreams,

so have data coming local server, know bytes read in follow format

0x01 specify string

then random amount of bytes

followed trailing 0x00 0x00,

i having trouble reading server though,

here method reading

    public static string convertfromserver(datainputstream dis) throws ioexception{     //buffer hold bytes being read in     bytearrayoutputstream buf = new bytearrayoutputstream();      if(dis.read() != -1){         //check see if first byte == 0x01     if(dis.read() == 0x01){         //check if byte dosnt equal 0x00, need check if 0x00 0x00         while(dis.read() != 0x00){             buf.write(dis.read());         }     }      if(dis.read() == 0x03){              while(dis.read() != 0x00){              buf.write(dis.read());         }     }     }     string messagerecevied = new string(buf.tobytearray());     return messagerecevied;  } 

if little ambiguous let me know.

i getting data , not correct, send across byte array, with first element being 0x01 specify string, string in bytes , last 2 elements 0x00 , 0x00, data sent me server, server receives data, when reading not correct, letter missing

this code writes encodes data nthe format 0x01, message in bytes, 0x00,0x00

  public static void writestringtobuffer(bytearrayoutputstream buf,string message){      buf.write(0x01);      byte[] b = message.getbytes();      for(int =1; i<message.getbytes().length+1;i++ ){          buf.write(b[i-1]);       }     buf.write(0x00);     buf.write(0x00);   } 

something gets me when i'm doing socket work making sure orders reversed on server , client.

if server reads first, client has write first. if server writes first, client has read first. if they're both trying read or both trying write, won't output.

my recommendation this:

if(dis.read() == 0x01) {     int zeroesinarow = 0;      while(zeroesinarow < 2) {         int b = dis.read()         if(b == 0x00) zeroesinarow++;         else zeroesinarow = 0;         buf.write(b);     }     string rawmessage = new string(buf.toarray());     // take off last 2 0s     string messagerecevied = rawmessage.substring(0,rawmessage.length()-2);     return messagerecevied; } 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -