With this code, we can create a Server Socket in Java to listen for incoming connections.
This code is made up of 2 classes, PortMonitor & OneConnection.
PortMonitor will open a desired port and watch for the incoming connection. Once a connection is established, the OneConnection class will relay back any incoming data.
Once this code is compiled, you can test it by using telnet to connect locally to the desired port.
import java.net.*; import java.io.*; public class PortMonitor { /** * JavaProgrammingForums.com */ public static void main(String[] args) throws Exception { //Port to monitor final int myPort = 101; ServerSocket ssock = new ServerSocket(myPort); System.out.println("port " + myPort + " opened"); Socket sock = ssock.accept(); System.out.println("Someone has made socket connection"); OneConnection client = new OneConnection(sock); String s = client.getRequest(); } } class OneConnection { Socket sock; BufferedReader in = null; DataOutputStream out = null; OneConnection(Socket sock) throws Exception { this.sock = sock; in = new BufferedReader(new InputStreamReader(sock.getInputStream())); out = new DataOutputStream(sock.getOutputStream()); } String getRequest() throws Exception { String s = null; while ((s = in.readLine()) != null) { System.out.println("got: " + s); } return s; } }
Example output:
port 101 opened
Someone has made socket connection
got: test