问题
Using Input/Output stream to pass objects between my client and server. I can both send and receive objects with my server, and and now i want the same for the client which as of now only can send. So i gave my client an ObjectInputStream. However, when i initilazie it, it blocks! Been searching around and found answers but no solution.
Please help!
public GameConnection(String strPort, TextArea chat)
{
this.port = Integer.parseInt(strPort);
System.out.println("GameConnection::Constructor(): Connecting on port " + port);
this.chat = chat;
connect = new Connection();
sendObject();
}
public void sendObject()
{
try
{
obj_stream.writeObject(new String("GameServer received a message!"));
}
catch(Exception e){System.out.println("GameConnection::sendObject(): " + e);}
}
protected class Connection extends Thread
{
private boolean alive = true;
public Connection()
{
try
{
socket = new Socket(host, port);
System.out.println("Connected to GAMESERVER" + host + " on port + " + port);
obj_stream = new ObjectOutputStream(socket.getOutputStream());
// Next line BLOCKS!!!
//ObjectInputStream stream = new ObjectInputStream(socket.getInputStream());
}
catch (IOException ioe)
{
System.out.println("Connection::constructor() " + ioe);
Terminate();
}
catch (NullPointerException npe)
{
System.out.println("Connection::constructor() " + npe);;
Terminate();
}
}
I tried using them in different threads but it had the same problem, at least for me :(
回答1:
yes, this question has been asked many times before. the object stream format has a header, and the ObjectInputStream reads that header on construction. therefore, it is blocking until it receives that header over the socket. assuming your client/server code looks similar, after you construct the ObjectOutputStream, flush it. this will force the header data over the wire.
来源:https://stackoverflow.com/questions/8088557/getinputstream-blocks