我在java中有一个简单的区块链的朴素p2p实现。
我正在尝试发送消息并在发送消息后等待立即响应,以便更新客户端的本地“bloomchain”变量。
我尝试使用期货和后台线程中运行的单个线程执行程序来执行此操作,但每次等待返回时都会出现以下错误:
java.util.concurrent.ExecutionException: java.io.StreamCorruptedException: invalid type code: 00
java.util.concurrent.ExecutionException: java.io.StreamCorruptedException: invalid type code: 6F
我认为问题可能是等待我设置线程,因为我没有这种经验:
发送消息:
public void sendMessage(String message) {
if (bloomChain.size() < 1) {
System.out.println("Genesis Block");
bloomChain.addBlock(new Block(message, "0"));
} else {
System.out.println("Augmented Block");
bloomChain.addBlock(new Block(message, bloomChain.get(bloomChain.size() - 1).getPreviousHash()));
}
try {
System.out.println("Sending Chain..");
this.outputStream.writeObject(bloomChain);
this.outputStream.flush();
new Thread(()-> {
try {
bloomChain = updateLocalChain();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println("Chain Sent..");
} catch (IOException e) {
e.printStackTrace();
}
}
更新本地链:
public BloomChain updateLocalChain() throws ExecutionException, InterruptedException {
Future<BloomChain> agreedChain = this.singleThreadExecutor.submit(new Callable<BloomChain>() {
@Override
public BloomChain call() throws IOException, ClassNotFoundException {
Object newChain = null;
while(true){
newChain = inputStream.readObject();
if(newChain instanceof BloomChain){
System.out.println(newChain.toString());
break;
}
}
return (BloomChain) newChain;
}
});
return agreedChain.get();
}
修改 在调试过程中,我发现程序收到了预期的响应,但无论如何都产生了错误
答案 0 :(得分:0)
你要么:
ObjectInputStream
时,为每条消息使用新的ObjectOutputStream
。为什么你使用线程同步做某事是另一个谜。