// File: IO7_server_plain.java (Module 13) // // Author: Rahul Simha // Created: Nov 13, 2000. // // Consumer as server, using sockets, with no frame. import java.io.*; import java.net.*; class Consumer implements Runnable { InputStream inStream; public Consumer (InputStream inStream) { this.inStream = inStream; } public void run () { // Read byte values until EOF. while (true) { // Get the next byte int i = -1; try { i = inStream.read (); } catch (IOException e) { System.out.println (e); } // Extract byte. byte k = (byte) i; // Check if end-of-data. if ( (i < 0) || (k < 0) ) break; System.out.println ("Consumer: just read " + k); // Sleep for a while. try { Thread.sleep ((int)UniformRandom.uniform(5,10)); } catch (InterruptedException e) { System.out.println (e); } } try { inStream.close (); } catch (IOException e) { System.out.println (e); } } } public class IO7_server_plain { public static void main (String[] argv) { try { // Create a listening service for connections // at the designated port number. ServerSocket srv = new ServerSocket (40013); // When a connection is made, get the socket. // The method accept() blocks until then. System.out.println ("Consumer as 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 ("Consumer as server: accepted a connection" + " from " + remoteMachine); // We are going to listen, so get an InputStream // and hand it over to the consumer. InputStream inStream = soc.getInputStream (); // Create a consumer instance and thread. Consumer c = new Consumer (inStream); Thread cthread = new Thread (c); // Start the thread. cthread.start(); } catch (IOException e) { System.out.println (e); } } }