import java.io.*; import java.net.*; import java.util.*; public class MultiTextReceiver { public static void main (String[] argv) { try { // Create a listening service for connections at the designated port number. ServerSocket srv = new ServerSocket (9003); int numConnections = 0; while (true) { // Wait for a connection to come in. System.out.println ("Server: waiting for a connection ..."); Socket soc = srv.accept (); // At this stage, the connection will have been made. InetAddress remoteMachine = soc.getInetAddress(); System.out.println ("Accepted a connection from " + remoteMachine); // We are going to listen, so get an InputStream InputStream inStream = soc.getInputStream (); LineNumberReader lnr = new LineNumberReader (new InputStreamReader (inStream)); numConnections ++; // Create an instance of a object that handles this connection in a separate thread. LineReaderObject lineReader = new LineReaderObject (lnr, numConnections); System.out.println ("Server: created connection ID=" + numConnections); // Start the thread: lineReader.start(); } //end-while } catch (IOException e) { System.out.println (e); } } } class LineReaderObject extends Thread { LineNumberReader lnr; int ID; public LineReaderObject (LineNumberReader lnr, int ID) { this.lnr = lnr; this.ID = ID; } // Override the run() method in Thread. This is what is called by the // thread once it starts. public void run () { // readLine() needs a try-catch. try { String line = lnr.readLine (); while (line != null) { System.out.println ("[I# " + ID + "] Received: " + line); line = lnr.readLine(); } } catch (IOException e) { System.out.println (e); } } }