// File: IO27_server.java (Module 13) // // Author: Rahul Simha // Created: Nov 28, 1998 // // Consumer as server, using sockets, with object streams. import java.io.*; import java.net.*; class Consumer implements Runnable { InputStream inStream; public Consumer (InputStream inStream) { this.inStream = inStream; } public void run () { try { // Open an ObjectInputStream. ObjectInputStream ois = new ObjectInputStream (inStream); // Read Person instances from the stream. Person p = (Person) ois.readObject(); System.out.println (p); p = (Person) ois.readObject(); System.out.println (p); ois.close(); } catch (IOException e) { System.out.println (e); } catch (ClassNotFoundException e) { System.out.println (e); } } } public class IO27_server { public static void main (String[] argv) { try { // Create a listening service for connections // at the designated port number. ServerSocket srv = new ServerSocket (5010); // 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); } } }