0

I have build a client-server application and the two are communicating via sockets and streams. My server creates these streams:

this.out = new DataOutputStream(sock.getOutputStream());
this.in = new DataInputStream(sock.getInputStream());
this.bufread = new BufferedReader(newInputStreamReader(sock.getInputStream()));

and then reads from the InputStream like that:

type = this.in.readByte();
String name = this.bufread.readLine();

Lastly the client writes to the OutputStream like this:

DataOutputStream out = new DataOutputStream(MyClient.getOutputStream());
out.writeByte(17);
out.writeBytes("value\n");

I am sending bytes from my client and the server is reading bytes. If I send chars, ints or anything else from the client will it still be read as bytes from the server? Does the specific function used ensure the type of data read?

1 Answer 1

3

You cannot wrap the same InputStream in two different objects (a DataInputStream and an InputStreamReader). They do not know about each other and will interfere with each other’s operation.

Wrap your socket’s InputStream in one object. Since you need to read raw bytes, a DataInputStream makes the most sense.

As you may have seen, you cannot use the readLine method of DataInputStream, because it is deprecated. Do not attempt to ignore that deprecation and use it anyway; it is deprecated for a reason, namely because it does not handle characters properly.

Ideally, you should use the readUTF method instead, but you must make sure that the server is sending character data using DataOutputStream.writeUTF for this to work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.