user2328999
user2328999

Reputation: 91

Error while using InputStreamReader with Java

I tried to send an int value from the client to the server. This is the client code that I'm using below:

_port   = 8071;
_socket = new Socket("localhost", _port);

Random rand = new Random();
int  n = rand.nextInt(50) + 1;
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream());
dos.writeInt(n);
dos.flush();

Server Code

try {
    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    ObjectInputStream in = null;
    in = new ObjectInputStream(socket.getInputStream());
    int ClientNumber= in.readInt();
    System.out.println(ClientNumber);
}

but I am getting an invalid stream header error.

invalid stream header: 0000002B at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:781) at java.io.ObjectInputStream.(ObjectInputStream.java:278) at ServiceRequest.run(ServiceRequest.java:24) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:680)

Does anyone know what is causing the error? Is my code setup improperly?

Upvotes: 0

Views: 1919

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

try to change it like this

try {
             //   input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            DataInputStream in = new DataInputStream(socket.getInputStream());
            int clientNumber= in.readInt();
            System.out.println(clientNumber);
}

it should work. ObjectInputStream can read only streams sent by ObjectOuputStream, it starts with a magic number (header) 0xACED, see http://docs.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500535

You're writing using a DataOutputStream and reading using an ObjectInputStream. You should be using DataInputStream instead:

// Note declaration and assignment in a single statement. There's no point in
// making it null first.
DataInputStream in = new DataInputStream(socket.getInputStream());

// Note use of camelCase for variable name
int clientNumber = in.readInt();

You should also get rid of input here: you're not reading from it, and as this looks like it's a stream of binary data, it's inappropriate to treat it as text.

Oh, and you should be closing the input stream in a finally block.

Upvotes: 1

Related Questions