gpt4 book ai didi

java - ObjectInputStream 导致崩溃

转载 作者:行者123 更新时间:2023-12-01 13:46:30 26 4
gpt4 key购买 nike

当我尝试从服务器发送一个对象时,我的计算机似乎崩溃了,第 27 行尝试接收该对象,我想我得到了一个无效的类型代码:0一次,但通常只是崩溃,所以我必须重新启动

          new Thread(){
public void run(){
boolean sent = false;
boolean threadStarted = false;
while(true){
if(game.changedTurns){
System.out.println(game.changedTurns);
if(!sent){
try{
System.out.println("attempt to send from player");
out.writeObject(game.getSquareColors());
System.out.println("sent");
sent = true;
//Thread.sleep(500);
sent = false;
}
catch(Exception ex){
System.out.println("player1 " +ex.getMessage());
}
}
}if(!threadStarted)
threadStarted = true;
new Thread(){
public void run(){
while(true){
try{
Object ob = in.readObject(); // line 27

System.out.println("Player received");
}
catch(Exception e){
System.out.println("player2 "+e.getMessage());
}
}
}
}.start();
}
}
}.start();
}

一个对象从另一个客户端发送到服务器,服务器在第 16 行接收并尝试发送对象:

 class Opponent implements Runnable{    
ObjectInputStream in2;
ObjectOutputStream out;
Opponent(ObjectInputStream in2, ObjectOutputStream out){
this.in2 = in2; //from opponent to player
this.out = out;
}
public void run(){
while(true){
try{
System.out.println("from opponent to server waiting");
Object o2 = in2.readObject();
if(o2 instanceof Color[]){
System.out.println("fee");
out.writeObject(o2); //line 16
out.flush();
}
}
catch(Exception e){
System.out.println("S2 " +e.getMessage());
}
}
}
}

}

最佳答案

对象 I/O 流在开始传输对象之前互相发送一些 header ,因此我的建议是在第 1 结尾处首先创建输出流,在第 2 结尾处创建输入流,然后在第 1 结尾处创建输入流,最后在end 2 创建输出流,反之亦然
计算机崩溃似乎是非常奇怪的结果,这种常见的对象 I/O 流错过了使用

关于java - ObjectInputStream 导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333820/

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