gpt4 book ai didi

java - Java 可选数据异常

转载 作者:行者123 更新时间:2023-11-30 02:57:12 25 4
gpt4 key购买 nike

我正在制作一个语音聊天程序,但出现了 OptionalDataException 错误,并且在添加语音之前我的代码从未遇到过此问题。语音通信由不同的套接字处理,因此我没有看到问题。

Code:

    public class Client implements Runnable {                                                   // CLIENT
private String msg;
public void run() {
try {
s1 = new Socket(ipAddress, port);
s2 = new Socket(ipAddress, 1210);
o1 = new ObjectOutputStream(s1.getOutputStream());
o1.writeObject(name);
serverListModel.addElement(name);
i1 = new ObjectInputStream(s1.getInputStream());
Thread voice = new Thread(new ClientAudio());
voice.start();
while(true) {
msg = (String) i1.readObject();
String[] namePart = msg.split("-");
if(namePart[0].equals("AddName") && !namePart[1].equals(name) && !serverListModel.contains(namePart[1])) {
serverListModel.addElement(namePart[1]);
}
if(namePart[0].equals("RemoveName") && !namePart[1].equals(name)) {
serverListModel.removeElement(namePart[1]);
}
if(!msg.equals(null) && !namePart[0].equals("AddName") && !namePart[0].equals("RemoveName")) {
chatWindow.append(msg+"\n");
}
}
} catch (IOException | ClassNotFoundException e) {
chatWindow.append("Server Closed");
e.printStackTrace();
try {
s1.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mainWindow(true);
}
}
}


flag

它被抛出到msg = (String) i1.readObject();并且它说

java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1361)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at client.chat$Client.run(chat.java:319)
at java.lang.Thread.run(Thread.java:745)

最佳答案

来自Oracle :

Exception indicating the failure of an object read operation due to unread primitive data, or the end of data belonging to a serialized object in the stream. This exception may be thrown in two cases:

  • 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.

  • An attempt was made to read past the end of data consumable by a class-defined readObject or readExternal method. In this case, the OptionalDataException's eof field is set to true, and the length field is set to 0.

看起来 Stream 中的下一个对象不是 String

服务器代码在您的控制之下吗?或者至少你有来源吗?如果是这样,请验证 String 对象是唯一正在传输的对象,或者调整您的代码以处理正在发送的实际对象/基元。

编辑

来自您的其他问题Voice Server not working :

byte[] soundData = 
//...
o.write(soundData, 0, bytesRead);

...看起来您没有将 String 对象写入 ObjectOutputStream。实际上,甚至不是写对象,而是原始字节。您必须以与写入数据相同的方式读取数据;其他任何事情都行不通。

关于java - Java 可选数据异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com