【发布时间】:2015-10-31 11:07:10
【问题描述】:
我无法从套接字获取输入和输出流,每次到达 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();
}
}
}
阻塞时没有输出错误。
【问题讨论】:
-
在创建 ObjectInputStream 之前始终刷新() ObjectOutputStream。这是因为该格式有一个 ObjectInputStream 在构造函数中读取的标头。
标签: java multithreading sockets objectinputstream