Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: can´t get ObjectInputStream from socket

I am doing java server client application and I have got problem. I succesfully get client´s socket, bud when I wanna make ObjectInputStream it stuck.

Code:

serverSocket = new ServerSocket(9999);

while(true){
    System.out.println("Waiting for player");
    Socket socket = serverSocket.accept();
    System.out.println("Player connected, waiting for command");

    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
    System.out.println("input created");      
}

Output:
Waiting for player Player connected, waiting for command

What can I do wrong?

like image 542
user3412372 Avatar asked Oct 19 '25 02:10

user3412372


1 Answers

The ObjectInputStream waits for an incoming header. Until the header is completly received you will be stuck at this line:

ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

to solve this problem you need to invoke flush() on the ObjectOutputStream on the other side (i.e. the server) as soon as the connection is established.

For more information read the javadoc.

like image 160
Markus Avatar answered Oct 21 '25 16:10

Markus