user3429531
user3429531

Reputation: 355

sending String using ObjectInputStream. Error: OptionalDataException

I am want to send a String - "HelloWorld" using ObjectInputStream from the client to server. The server will receive "HelloWorld" and print it out on console.

Both of them are connected on localhost and port 4445.

I received a error at the server side

Error: java.io.OptionalDataException

Client.java

private ObjectOutputStream output;  
private ObjectInputStream input;    

@Override
public void run() { 
        try {
            socket = new Socket("localhost",4445);
            output = new ObjectOutputStream(socket.getOutputStream());
            input = new ObjectInputStream(socket.getInputStream());
            output.writeChars("HelloWorld");
            output.flush();
        }   
}

Server.java

private ObjectOutputStream output;  
private ObjectInputStream input;    
private Object message;

@Override
public void run() {         
    try {       
        output = new ObjectOutputStream(socket.getOutputStream());
        input = new ObjectInputStream(socket.getInputStream()); 
        while(true) {   
            try {
                message =(String)input.readObject();
                System.out.println(message);

            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       
        }
   }catch(IOException exception) {
        System.out.println("Error: " + exception);
    }

I read up on this error and it states that this exception will be thrown when

An attempt was made to read an object when the next element in the stream is 
primitive data. In this case, the OptionalDataException's length field is set
to the number of bytes of primitive data immediately readable from the stream, 
and the eof field is set to false.

I am quite lost after reading this explanation, so does that mean that you cannot send a String data type using ObjectInputStream?

Upvotes: 1

Views: 1105

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Chars sent by writeChars can be read only by several readChar. Use writeUTF / readUTF instead

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44854

when you are using writeChars you are not writing A string you are writing a series of primitives. Use writeObject instead.

As per javaDocs

public void writeChars(String str)
                throws IOException
Writes a String as a sequence of chars.

Upvotes: 1

Related Questions