java初始化流入/出的变量

时间:2011-02-06 17:09:02

标签: java objectinputstream datainputstream

我遇到以下代码的问题。目前尚不清楚如何初始化输入/输出的变量。

在创建此对象期间,程序在构造函数中挂起。它挂在this.inObjects = new ObjectIn.........的行上。我想创建那些输入/输出对象只需要在输入/输出,字符串和对象上读取和写入,只需在方法中调用它们并应用读写等等。

我哪里错了?是否有可能通过不接收数据而挂起?他们不应该,对吧?

public class PokerClient 
{
    private PokerClientGui gui;
    private Socket clientSocket;
    private DataInputStream in;
    private DataOutputStream output;
    private ObjectInputStream inObjects;
    private ObjectOutputStream outObjects;
    private Hand hand;

    //constructor
    public PokerClient()
    {
        try
        {
            this.gui= gui;
            this.clientSocket = new Socket("localhost", 4444);
            this.in = new DataInputStream(this.clientSocket.getInputStream());
            this.inObjects = new ObjectInputStream(this.clientSocket.getInputStream());
            this.output = new DataOutputStream(this.clientSocket.getOutputStream());
            this.outObjects = new ObjectOutputStream(this.clientSocket.getOutputStream());
        }
        catch (Exception e)
        {
        }
}

2 个答案:

答案 0 :(得分:2)

您应该始终首先创建对象输出流并将其刷新。您永远不应该以两种不同的方式包装相同的流。永远不要捕获异常并忽略它,除非你喜欢有错误并且无法确定出错的地方。不要为自己分配一个字段,这不会做任何有用的事情,只会让人迷惑。

public class PokerClient {
  private final PokerClientGui gui;
  private final Socket clientSocket;
  private final ObjectOutputStream outObjects;
  private final ObjectInputStream inObjects;

  public PokerClient(PokerClientGui gui) throws IOException {
    this.gui = gui;
    clientSocket = new Socket("localhost", 4444);
    outObjects = new ObjectOutputStream(clientSocket.getOutputStream());
    outObjects.flush();
    inObjects = new ObjectInputStream(clientSocket.getInputStream());
  }
}

答案 1 :(得分:1)

交换两行,即使用此顺序:

this.outObjects = new ObjectOutputStream(this.clientSocket.getOutputStream());
this.inObjects = new ObjectInputStream(this.clientSocket.getInputStream());

OIS的构造函数等待一些标题,你必须先发送,否则它总是阻塞。