我想使用 ObjectInputStream 从客户端向服务器发送一个字符串 - “HelloWorld”。 服务器将收到“HelloWorld”并在控制台上打印出来。
它们都连接在本地主机和端口 4445 上。
我在服务器端收到错误
Error: java.io.OptionalDataException
客户端.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();
}
}
服务器.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 数据类型?
最佳答案
当您使用writeChars
时,您不是在编写字符串,而是在编写一系列原语。请改用writeObject
。
根据 javaDocs
public void writeChars(String str)
throws IOException
Writes a String as a sequence of chars.
关于java - 使用 ObjectInputStream 发送字符串。错误: OptionalDataException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25541053/