使用ObjectInputStream发送String。错误:OptionalDataException

时间:2014-08-28 05:03:20

标签: java sockets

我想从客户端到服务器使用ObjectInputStream发送一个String - “HelloWorld”。 服务器将收到“HelloWorld”并在控制台上打印出来。

它们都连接在localhost和端口4445上。

我在服务器端收到错误

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);
    }

我读到了这个错误,它声明在

时会抛出此异常
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.

阅读完这篇解释后,我很遗憾,这是否意味着您无法使用ObjectInputStream发送String数据类型?

2 个答案:

答案 0 :(得分:1)

当你使用writeChars时,你没有写一个字符串,你正在编写一系列基元。请改用writeObject

根据javaDocs

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

答案 1 :(得分:0)

writeChars发送的字符只能被多个readChar读取。请改用writeUTF / readUTF