gpt4 book ai didi

java - 对象输入流 : is this correct way to unblock

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:46 25 4
gpt4 key购买 nike

ObjectInputStream 在创建时会阻塞,直到收到串行输入流并对其进行验证。我试图通过它使用套接字来制作我的第一个程序并发现了这个。我使用了一个虚拟对象,这样它就不会阻塞。代码在这里:

import java.io.*;                      
import java.net.*;
import java.util.*;

class Dummy implements Serializable {
}

class X_Int implements Serializable {
int x;
}

class Server {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(5879);
Socket client = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(new Dummy());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
in.readObject();
out.flush();
out.writeObject(new Date());
out.flush();
out.close();
}
}

class Client {
public static void main(String args[]) throws Exception {
Socket server = new Socket("localhost", 5879);
ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());
out.writeObject(new Dummy());
ObjectInputStream in = new ObjectInputStream(server.getInputStream());
in.readObject();
out.flush();
Date d = (Date)in.readObject();
System.out.println(d);
}
}

这是正确的方法吗?请评论。

最佳答案

您只需在创建对象输入流之前刷新()输出即可。您不需要发送虚拟对象。

关于java - 对象输入流 : is this correct way to unblock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328184/

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