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.
Create a ServerSocket , specifying a port to listen on. Invoke the ServerSocket 's accept() method to listen on the configured port for a client connection. When a client connects to the server, the accept() method returns a Socket through which the server can communicate with the client.
Yes, Socket and ServerSocket use TCP/IP. The package overview for the java.net package is explicit about this, but it's easy to overlook. UDP is handled by the DatagramSocket class.
Procedure: In order to create a socket, the 'java.net' package needs to be imported thereafter using the Socket and ServerSocket class, we create the object of that class. The Server opens a ServerSocket on a well-known port and waits for input.
You need to use a ServerSocket
. You can find an explanation here.
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.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With