我无法从套接字获取输入和输出流,每次到达getInputStream / getOutputStream时,我的代码都会阻塞。
class Connection implements Runnable {
private static final Logger logger = Logger.getLogger(Connection.class.getName());
Socket connection = null;
Boolean serverIsDown = false;
Thread thread = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Context ctx = null;
public Connection(Socket accept, Boolean serverIsDown) {
logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress());
this.connection = accept;
this.serverIsDown = serverIsDown;
this.thread = new Thread(this, "Client Connection");
this.thread.start();
}
public void init() throws IOException {
while (true) {
System.out.println("Hit enter to send object");
System.in.read();
Request request = new Request();
oos.writeObject(request);
}
}
@Override
public void run() {
try {
this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here
this.oos = new ObjectOutputStream(this.connection.getOutputStream());
this.init();
} catch (IOException e) {
e.printStackTrace();
}
}
}
阻塞时没有输出错误。
就像提到的文档一样:http : //docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)
创建一个ObjectInputStream,它从指定的InputStream读取。从流中读取并验证序列化流头。此构造函数将阻塞,直到相应的ObjectOutputStream写入并刷新了标头为止。
我建议您使用两个线程来处理来自接受的套接字的输入和输出流,以避免阻塞。另一种更好的方法是使用线程池和一些异步io(例如;选择器),而不是为每个接受的套接字分配线程。
也可以参考以下另一篇文章:new ObjectInputStream()块
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句