// File: IO8_server.java (Module 13) // // Author: Rahul Simha // Created: Nov 28, 1998 // // Producer as server, using sockets. import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class Producer extends Frame implements Runnable { Label L; // A place to write stuff. OutputStream out_stream; public Producer (OutputStream out_stream) { // Store the reference to the output stream. this.out_stream = out_stream; // Create the frame. this.setSize (600,100); this.setLocation (0,100); this.setTitle ("Producer"); this.setBackground (Color.white); // this.setLayout (new BorderLayout()); // This is where we will write to. L = new Label (""); this.add (L, BorderLayout.CENTER); this.setVisible (true); } // Must implement the run() method. public void run () { // Write 25 random bytes to the buffer. for (int i=1; i<=25; i++) { // Create a random byte byte k = (byte) UniformRandom.uniform (1, 100); // Write to label first. L.setText (L.getText() + " " + k); // Write it to the screen. System.out.println ("Producer: writing " + k); // Write integer to buffer. try { out_stream.write (k); } catch (IOException e) { System.out.println (e); } // Sleep for a while. try { Thread.sleep ((int)UniformRandom.uniform(100,1000)); } catch (InterruptedException e) { System.out.println (e); } } // Write EOF and close output stream. try { out_stream.write (-1); out_stream.close (); } catch (IOException e) { System.out.println (e); } L.setText (L.getText() + " Done!"); } } // This is an independent quit button to quit the application. class QuitButton extends Frame { public QuitButton () { this.setSize (80,50); this.setLocation (0, 0); this.setTitle ("Quit button"); Button quitb = new Button ("QUIT"); quitb.setBackground (Color.red); quitb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); this.add (quitb, BorderLayout.CENTER); this.setVisible (true); } } public class IO8_server { public static void main (String[] argv) { // Create an independent quit button. QuitButton q = new QuitButton (); 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 ("Producer as server: waiting for a connection"); Socket soc = srv.accept (); // At this stage, the connection will have been made. InetAddress remote_machine = soc.getInetAddress(); System.out.println ("Consumer as server: accepted a connection" + " from " + remote_machine); // We are going to write, so get the output stream. OutputStream out_stream = soc.getOutputStream (); // Create a producer instance and thread. Producer p = new Producer (out_stream); Thread pthread = new Thread (p); // Start the threads. pthread.start(); } catch (IOException e) { System.out.println (e); } } }