
import java.io.*;
import java.net.*; 

/* 
  Protocol --- Ticker client pull 

  Port:   8001 
 
  Client: connect
  Server: name1 quote1
          name2 quote2
	  ...
  Server: disconnect 

  Server design:
  two threads: client handler, quote generator 
  no synchronization necessary for quote[] 
*/ 

public class QuotePullServer extends Thread {

  static protected String symbol[] = { "IBM", "Sun", "Intel", "Apple", "Compaq" }; 
  static protected int    quote[] = { 100, 100, 100, 100, 100 }; 
  static protected int    n = 5; 

  public static void main(String[] args) {
    System.out.println("QuotePullServer started."); 

    new QuotePullServer().start(); 

    try {
      ServerSocket s = new ServerSocket(8001); 
      for (;;) {
	Socket incoming = s.accept(); 
	PrintWriter out =
	    new PrintWriter(new OutputStreamWriter(incoming.getOutputStream())); 
	for (int i = 0; i < n; i++) {
	  out.println(symbol[i] + " " + quote[i]); 
	}
	out.flush(); 
	out.close(); 
	incoming.close(); 
      }
    } catch (Exception e) {
      System.err.println(e); 
    }
    System.out.println("QuotePullServer stopped."); 
  }

  public void run() {
    while (true) {
      try {
	Thread.currentThread().sleep(10000); 
	System.out.println("New quote:");
	for (int i = 0; i < n; i++) {
	  quote[i] += (Math.random() - 0.4) * ( 10.0 * Math.random());   
	  System.out.println(symbol[i] + " " + quote[i]);
	}
	System.out.println("End quote.");
      } catch (Exception e) {
	System.err.println(e); 
      }
    }
  }

}
