I am trying to connect to WebSocket (currently using the chrome extension). I got it working that I receive the data. When I try to convert the integers I receive from the input stream I get totally other values. In the example below I gave in the word test as input. So do I do something wrong or do I interpret the input wrong?
Code:
@Override
public void run() {
while (true) {
try {
if(client.getInputStream().read() != -1) {
int i = client.getInputStream().read();
System.out.println("Integer: " i);
byte b = (byte) i;
System.out.println("Byte: " b);
char c = (char) b;
System.out.println("Char: " c);
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
CodePudding user response:
A java stream returns bytes, but read returns an int so that you can get -1. So if your server is sending an int, then you need to read all of the bytes for that int and create it.
You have two ways to do this. Create a byte[] and use it as a buffer or if you're receiving 32 bit twos complement integers then you can use a DataInputStream.
An example using a buffer.
@Override
public void run() {
while (true) {
try {
byte[] buffer = new byte[4];
if(client.getInputStream().read(buffer) != -1) {
int i = (
( ( buffer[0] & 0xff ) << 24 ) |
( ( buffer[1] & 0xff ) << 16 ) |
( (buffer[2] & 0xff ) << 8) |
(buffer[3] & 0xff)
);
System.out.println("Integer: " i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Or you can use a DataInputStream.
DataInputStream dis = new DataInputStream(client.getInputStream());
try{
int i = dis.readInt();
} catch( EOFException e){
//end of file. This is like getting -1.
} catch( IOException e ){
//do something for an error
}
The buffer version uses the same conversion as java's DataInput.readInt, I've included it for an example. Also there is some additional checking that should be done. Even though the buffer is 4 bytes long, you could read anything from 1 to 4 bytes.