我对 ByteArrayInputStream + ObjectInputStream (和相应的输出流)有疑问。
我想Pair
通过 UDP 通道编写该类的一些(不同)实例,并且我已经做到了:
对于写作 ( this.scores
is a HashMap<String, Integer>
and this.completed
is an ArrayList<String>
(假设它size()
在这个例子中是 2))
for(String userWhoCompleted : this.completed) {
try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);) {
oos.writeUnshared(new Pair<String, Integer>(userWhoCompleted, this.scores.get(userWhoCompleted)));
oos.flush();
this.resultChannel.write(ByteBuffer.wrap(baos.toByteArray()));
} catch(IOException e) { e.printStackTrace(); }
}
用于阅读(buf
是一个ByteBuffer
)
while(scoresReceived != 2) { // 2 is temporary
buf.clear();
try {
this.multicastChannel.receive(buf);
} catch(IOException e) { e.printStackTrace(); }
try(ByteArrayInputStream bais = new ByteArrayInputStream(buf.array(), 0, buf.position());
ObjectInputStream ois = new ObjectInputStream(bais);) {
Pair<String, Integer> result = (Pair<String, Integer>) ois.readUnshared();
System.out.println(result);
} catch(IOException | ClassNotFoundException e) { e.printStackTrace(); }
}
使用此代码,我可以正确读取通道上写入的所有 2 个对象。
但是正如你所看到的,我必须在每个新的循环周期上创建一个,和baos
的新实例。我试图在循环之外创建这些对象,然后分别在服务器和客户端执行 +和,但我在阅读时得到了。如果我删除我总是读取相同的对象,那是第一个写入. 我做错了什么?这是解决这些问题的唯一方法吗?oos
ois
bais
oos.writeUnshared(baos.toByteArray)
baos.reset()
readUnshared
StreamCorruptedException: invalid stream header
baos.reset()
oos
PS:课程Pair
是Serializable
:
import java.io.Serializable;
public class Pair<F extends Serializable, S extends Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
private F first;
private S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() { return first; }
public S getSecond() { return second; }
public String toString() {
return "First: " + this.first.toString() + " Second: " + this.second.toString();
}
}