Rahul
Rahul

Reputation: 83

Java DataInputStream

Client side:

        out = new DataOutputStream(connection.getOutputStream());
        String process;
        System.out.println("Connecting to server on "+ host + " port " + port +" at " + timestamp);
        process = "Connection: "+host + ","+port+","+timestamp; 
        System.out.println("client len " + process.length());
        out.write(process.length());

Prints: Client len 55

Server side:

       in = new DataInputStream(connection.getInputStream());
       while (true) {
            int len = in.readInt();
            System.out.println("Length of pkt: "+len);

Prints: Length of pkt: 927166318

What's going on here? I tried writing 0 and it printed 3621743 on the server side. I checked some other sites and a few people had problems with other streams. I read about the issues arising with big vs little endianness, but I am not sure what the problem is here since I am using the data*streams that should work fine with each other.

Upvotes: 1

Views: 81

Answers (2)

rogi1609
rogi1609

Reputation: 438

Use out.writeInt(process.length()); instead of out.write(...); since you read an Integer from the stream afterwards.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

If you call readInt() on one side, you should call writeInt(int) on the other. Change this

out.write(process.length());

to

out.writeInt(process.length());

From the Javadoc for write(int),

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Upvotes: 3

Related Questions