public class QuotePullServer extends Thread
1:
2: import java.io.*;
3: import java.net.*;
4:
5: /*
6: Protocol --- Ticker client pull
7:
8: Port: 8001
9:
10: Client: connect
11: Server: name1 quote1
12: name2 quote2
13: ...
14: Server: disconnect
15:
16: Server design:
17: two threads: client handler, quote generator
18: no synchronization necessary for quote[]
19: */
20:
21: public class QuotePullServer extends Thread {
22:
23: static protected String symbol[] = { "IBM", "Sun", "Intel", "Apple", "Compaq" };
24: static protected int quote[] = { 100, 100, 100, 100, 100 };
25: static protected int n = 5;
26:
27: public static void main(String[] args) {
28: System.out.println("QuotePullServer started.");
29:
30: new QuotePullServer().start();
31:
32: try {
33: ServerSocket s = new ServerSocket(8001);
34: for (;;) {
35: Socket incoming = s.accept();
36: PrintWriter out =
37: new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()));
38: for (int i = 0; i < n; i++) {
39: out.println(symbol[i] + " " + quote[i]);
40: }
41: out.flush();
42: out.close();
43: incoming.close();
44: }
45: } catch (Exception e) {
46: System.err.println(e);
47: }
48: System.out.println("QuotePullServer stopped.");
49: }
50:
51: public void run() {
52: while (true) {
53: try {
54: Thread.currentThread().sleep(10000);
55: System.out.println("New quote:");
56: for (int i = 0; i < n; i++) {
57: quote[i] += (Math.random() - 0.4) * ( 10.0 * Math.random());
58: System.out.println(symbol[i] + " " + quote[i]);
59: }
60: System.out.println("End quote.");
61: } catch (Exception e) {
62: System.err.println(e);
63: }
64: }
65: }
66:
67: }