1

Hey I'm trying to debug this program from last 2-3 days . Here is the problem ,I'm building a client server architecture and all clients ping server(with their information) after certain interval of time using Socket connection.So at server side when i try to construct a ObjectOutputStream the program get stuck. Here is code of client.

 public void pingUpdate(){
    Thread pingThread = new Thread() {
    public void run() {
        while(true) {
             try { 
                ping_socket = new Socket( "localhost", 11111 );
                ObjectOutputStream ping_objectOutputStream = new ObjectOutputStream( ping_socket.getOutputStream( ) );
                ping_objectOutputStream.flush();

                ping_objectOutputStream.writeObject( user );

                ping_objectOutputStream.close();

                ping_socket.close( );

             }catch (Exception exception) {
               exception.printStackTrace();
            }
           }
   };
    pingThread.start();
}

And here is the code of server

  public void run() {
while ( true ) {
      try {

            System.out.println("Server Listening" );

            Socket client = null;

            client = serverSock.accept();
            System.out.println("Accepted" );

             InputStream inputStream = client.getInputStream();

             System.out.println("Input stream established" );

             ObjectInputStream ois = new ObjectInputStream( inputStream );

              System.out.println("Object streams established" );

              User user = ( User ) ois.readObject( );

              System.out.println("Object read" );

               ois.close( );
               client.close( );
             }
              catch (Exception e){
                     e.printStackTrace();
                 }
         }
    }

The server program prints till "Input streams established" and get stuck. I don't know why this happens although i flushed the output stream at client side.Thanks.

4
  • 2
    You should create your stream once. Your pingThread creates a new ObjectOutputStream on every loop. You might want to go through some networking tutorials too, otherwise you'll be debugging for weeks. Commented Nov 4, 2016 at 7:59
  • If an exception is thrown you aren't closing the socket. Commented Nov 4, 2016 at 10:15
  • @Kayaman what is the problem with creating ObjectOutputStream on every iteration of the loop? Commented Jul 9, 2017 at 6:20
  • 1
    It's just wasteful. Instead of keeping a connection open and pinging on that, you reconnect every time. Sort of like if you hung up and redialed after every word in a phone conversation. Commented Jul 9, 2017 at 12:54

1 Answer 1

1

I can not reproduce the hanging client. I think it have to do how you write the object to the stream without flushing the stream afterwards, because streams are only flushed when they are full or before closing. Please use finally blocks to close the sockets and streams.

I have rewritten your source code and send a String "Hallo, Server" instead of the User object (which is missing in the code you provided). I added a little delay after sending, for not flooding the server with connections.

I have tested the code on Win 8.1 with JDK 1.8 Update 102 and it works now.

Client:

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client{

   public static void main(String[] args){

      new Client().pingUpdate();
   }

   public void pingUpdate(){

      Thread pingThread = new Thread(){

         @Override
         public void run(){

            while(true){
               Socket ping_socket = null;
               ObjectOutputStream ping_objectOutputStream = null;
               try{
                  ping_socket = new Socket("localhost",
                                           11111);
                  ping_objectOutputStream = new ObjectOutputStream(ping_socket.getOutputStream());

                  ping_objectOutputStream.writeObject("Hallo, Server");
                  ping_objectOutputStream.flush();
               }
               catch(Exception exception){
                  exception.printStackTrace();
               }
               finally{
                  try{
                     if (ping_objectOutputStream != null){
                        ping_objectOutputStream.close();
                     }
                  }
                  catch(IOException e){
                     e.printStackTrace();
                  }
                  try{
                     if (ping_socket != null){
                        ping_socket.close();
                     }
                  }
                  catch(IOException e){
                     e.printStackTrace();
                  }
               }

               // wait some time for the next ping
               try{
                  Thread.sleep(1000);
               }
               catch(InterruptedException e){
                  e.printStackTrace();
               }
            }
         }
      };
      pingThread.start();
   }
}

Server:

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server{

   public void servePingUpdate(){

      Thread pingThread = new Thread(){

         @Override
         public void run(){

            ServerSocket serverSock = null;
            try{
               serverSock = new ServerSocket(11111);

               while(true){
                  Socket client = null;
                  ObjectInputStream ois = null;

                  try{
                     System.out.println("Server Listening");

                     client = serverSock.accept();
                     System.out.println("Accepted");

                     InputStream inputStream = client.getInputStream();

                     System.out.println("Input stream established");

                     ois = new ObjectInputStream(inputStream);

                     System.out.println("Object streams established");

                     String message = (String) ois.readObject();

                     System.out.println("Object read: " + message);
                  }
                  catch(Exception e){
                     e.printStackTrace();
                  }
                  finally{
                     try{
                        if (ois != null){
                           ois.close();
                        }
                     }
                     catch(IOException e){
                        e.printStackTrace();
                     }
                     try{
                        if (client != null){
                           client.close();
                        }
                     }
                     catch(IOException e){
                        e.printStackTrace();
                     }
                  }
               }
            }
            catch(IOException e1){
               e1.printStackTrace();
            }
            finally{
               try{
                  if (serverSock != null){
                     serverSock.close();
                  }
               }
               catch(IOException e){
                  e.printStackTrace();
               }
            }
         }
      };
      pingThread.start();
   }

   public static void main(String[] args){

      new Server().servePingUpdate();
   }
}

EDIT: The TCP protocol needs some time to do the TCP handshake and the server takes some time to output the lines over System.out and to close the socket.

Without the wait in the client throws a java.net.BindException: Address already in use: connect after 1-2 seconds, because the server is out of usable ports. For low latency pinging the UDP protocol is better, see example code for a UDP pinger or keep the socket open and reuse it for every ping.

Sign up to request clarification or add additional context in comments.

1 Comment

Adding sleeps into networking code doesn't solve them. It only delays them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.