简体   繁体   中英

Help needed with reading data from server in java

i am having a bit of trouble with DataInputStreams,

So i have data coming for a local server, i know that the bytes i read in will follow this format

0x01 to specify it is a string

then random amount of bytes

followed by trailing 0x00 0x00,

i am having trouble reading from the server though,

here is my method for reading

    public static String convertFromServer(DataInputStream dis) throws IOException{
    //Buffer to hold bytes being read in
    ByteArrayOutputStream buf = new ByteArrayOutputStream();

    if(dis.read() != -1){
        //Check to see if first byte == 0x01
    if(dis.read() == 0x01){
        //Check if byte dosnt equal 0x00, i need it to check if it is actually 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 i am a little ambiguous let me know.

i am getting data back , its just not fully correct, basically what i do is send across a byte array, with with the first element being 0x01 to specify string, then the string in bytes and then finally the last 2 elements are 0x00 and 0x00, then this data is then sent back to me from the server, the server definitely receives the data, just when i am reading back it not correct, letter will be missing

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

  public static void writeStringToBuffer(ByteArrayOutputStream buf,String message){

    buf.write(0x01);

    byte[] b = message.getBytes();

    for(int i =1; i<message.getBytes().length+1;i++ ){

        buf.write(b[i-1]);

     }
    buf.write(0x00);
    buf.write(0x00);


}

Something that always gets me when I'm doing socket work is making sure the orders are reversed on the server and the client.

If the server reads first, the client has to write first. If the Server writes first, the client has to read first. If they're both trying to read or both trying to write, you won't get any output.

My recommendation is to do 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 the last two 0s
    String messageRecevied = rawMessage.substring(0,rawMessage.length()-2);
    return messageRecevied;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM