java initializing variable for stream in/out
I have a problem with the below code. It is not clear how I can initialize the variables of in/out.
During the creation of this object the program hangs when in the constructor. It hangs at the line of the this.inObjects = new ObjectIn.........
. I would like to create those in/out objects once only to read and write on the input/output, strings and objects by just calling them in the methods and applying read write etc etc
Where am I going wrong开发者_如何学Go? Is it possible that by not receiving data they hangs? They shouldn't, right?
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)
{
}
}
You should always create the object output stream first and flush it. You should never wrap the same stream two different ways. Never catch an exception and ignore it unless you like having errors and no way to determine what has gone wrong. Don't assign a field to itself, this won't do anything useful, it will just confuse people.
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());
}
}
Swap the two lines, i.e., use this order:
this.outObjects = new ObjectOutputStream(this.clientSocket.getOutputStream());
this.inObjects = new ObjectInputStream(this.clientSocket.getInputStream());
The constructor of OIS waits for some header, you must send first, otherwise it always blocks.
精彩评论