[java] Listen to port via a Java socket

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.)

I tried this code but it doesn’t output anything:

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();
        }
    }
}

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.

I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.

This question is related to java sockets

The answer is


What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)


Try this piece of code, rather than ObjectInputStream.

BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}