开发者

Help needed with reading data from server in java

开发者 https://www.devze.com 2023-02-13 12:50 出处:网络
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

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消