title: Listen to port via a Java socket
body: <p>A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)</p>
  
  <p>I tried this code but it doesn’t output anything:</p>
  
  <pre><code>package merchanttransaction;
  
  import java.io.IOException;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
  import java.lang.ClassNotFoundException;
  import java.net.InetAddress;
  import java.net.Socket;
  import java.net.UnknownHostException;
  
  public class MerchantTransaction {
      public static void main(String[] args) {
          try {
              InetAddress host = InetAddress.getLocalHost();
              Socket socket = new Socket("192.168.1.104", 4000);
              ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
              String message = (String) ois.readObject();
              System.out.println("Message: " + message);
  
              ois.close();
          } catch (UnknownHostException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } catch (ClassNotFoundException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.</p>
  
  <p>I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.</p>