gpt4 book ai didi

java - 客户端 - 服务器 ObjectInputStream 错误

转载 作者:行者123 更新时间:2023-11-30 04:48:26 25 4
gpt4 key购买 nike

我的代码是这样的

try
{
//Connect to the login server
socket = new Socket(hostName , 15000);
out = new ObjectOutputStream(socket.getOutputStream());
input = new ObjectInputStream(socket.getInputStream());

.. //perform the login , if the login succeed make answ=1;
}
catch (UnknownHostException e) {
System.err.println("Unknown host: " + hostName);
StatusLabel.setText("Unknown host");
}
catch (ConnectException e) {
System.err.println("Connection refused by host: " + hostName);
StatusLabel.setText("Connection refused by host, server is down.");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try
{
//Finaly closing the connection
socket.close();
System.out.flush();
System.out.println("Socket Closed");
//closing the output and input stream
out.close();
input.close();
setVisible(false); //closing the window
}
catch (IOException e ) {
System.out.println("Couldn't close socket");
}
}
if(answ==1) //if the login suceed start the class for the game
{
Gumoku_Graphics g = new Gumoku_Graphics();
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.Play();
}

在Gumoku_Graphics()内部我调用这个类来执行与游戏服务器的连接

Game n = new Game();
status=n.Connection();

这是

 public int Connection()  
{
try {
socket = new Socket(hostName, 15432);
System.out.println("socket ok\n");

out = new ObjectOutputStream(socket.getOutputStream());
System.out.println("out ok\n");


input = new ObjectInputStream(socket.getInputStream());
System.out.println("socket,out,input ok\n");
return 1;
}

catch (UnknownHostException e) {
System.err.println("Unknown host: " + hostName);
return 0;
}
catch (ConnectException e) {
System.err.println("Connection refused by host: " + hostName);
return 0;
}
catch (IOException e) {
e.printStackTrace();
return 0;
}
}

并且每次它停止在“input = new ObjectInputStream(socket.getInputStream());”它无法做到这一点并且卡在那里。它打印“socket ok”、“out ok”并且卡在那里。有什么问题?我做错了什么?

最佳答案

来自ObjectInputStream documentation :

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

正如引用的那样,调用将阻塞,直到可以读取 header 。在继续此调用之前,您需要从套接字接收一些数据。

关于java - 客户端 - 服务器 ObjectInputStream 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388253/

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