gpt4 book ai didi

java - readObject 挂起应用程序

转载 作者:行者123 更新时间:2023-12-01 13:09:56 25 4
gpt4 key购买 nike

我正在尝试创建一个实时消息应用程序。但是,当尝试从 ObjectInputStream 读取对象时,代码无缘无故地挂起。没有抛出异常。

try {
System.out.println("Trying to connect to server");
socket = new Socket(InetAddress.getByName("localhost"),6789);
System.out.println("Connected to server");

inputStream = new ObjectInputStream(socket.getInputStream());

outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();

System.out.println("Streams are set up.");

window.toggleTyping(true);
System.out.println("Typing is now enabled");

String inputMsg = null;

do {
try {
System.out.println("Reading object");
inputMsg = (String)inputStream.readObject();
System.out.println("Object read");

} catch(ClassNotFoundException ee) {
System.out.println("Clas not found exception");
ee.printStackTrace();
}

} while(!inputMsg.equalsIgnoreCase("/exit"));

closeConnection();

}catch(IOException ex) {
ex.printStackTrace();
}

打印的最后一条消息是“Reading object”。

 try {
serverSocket = new ServerSocket(6789);
System.out.println("Socket created. About to accept connections");
Socket s = serverSocket.accept();
new Thread(new Chat(s)).start();

} catch(IOException e) {
e.printStackTrace();
}

和类(class)聊天:

    public class Chat implements Runnable {

private Socket socket;
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;

public Chat(Socket s) {
System.out.println("Chat class constructor called");
this.socket = s;

try {
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();

inputStream = new ObjectInputStream(socket.getInputStream());
System.out.println("Chat streams are now set up");

}catch(IOException ex) {
ex.printStackTrace();
}


}
private void closeChat() {
try {
outputStream.close();
inputStream.close();
socket.close();
System.out.println("Chat is now closed");
}catch(IOException ex) {
ex.printStackTrace();
}

}

@Override
public void run() {
System.out.println("Chat class method run called");
try {
outputStream.writeObject("Connection is cool");
outputStream.flush();
System.out.println("Text sent");
String inputMsg = "";
do {

try {
inputMsg = (String)inputStream.readObject();
System.out.println("Message read:"+inputMsg);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
while(!inputMsg.equalsIgnoreCase("/exit"));
closeChat();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

每次聊天都是不同线程的原因是我计划有一天实现多个一对一聊天。

最佳答案

这是因为读取方法是阻塞方法。这意味着它正在尝试读取,直到得到-1,表明读取数据已完成。确保写入此套接字的 OutputStream 正在发送此消息。因此,您在发送套接字时调用 ObjectOutputStream.flush();写入数据后的方法或在写入后关闭输出流。关闭此流是不合理的,因为稍后您可能希望通过此流发送更多数据。

<小时/>

只是一般情况:创建输出流后不需要立即刷新它

关于java - readObject 挂起应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22962932/

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