KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > net > core > SimpleServer


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.net.core;
5
6 import com.tc.net.TCSocketAddress;
7 import com.tc.net.protocol.EchoSink;
8 import com.tc.net.protocol.GenericNetworkMessageSink;
9 import com.tc.net.protocol.GenericProtocolAdaptor;
10 import com.tc.net.protocol.ProtocolAdaptorFactory;
11 import com.tc.net.protocol.TCProtocolAdaptor;
12
13 import java.io.IOException JavaDoc;
14
15 /**
16  * A simple server instance that accepts GenericNetwork messages and delivers them to a sink
17  *
18  * @author teck
19  */

20 public class SimpleServer {
21   final GenericNetworkMessageSink sink;
22   TCConnectionManager connMgr = new TCConnectionManagerFactory().getInstance();
23   TCListener lsnr;
24   final int port;
25
26   public SimpleServer(GenericNetworkMessageSink sink) {
27     this(sink, 0);
28   }
29
30   public SimpleServer(GenericNetworkMessageSink sink, int port) {
31     this.sink = sink;
32     this.port = port;
33   }
34
35   public void start() throws IOException JavaDoc {
36     TCSocketAddress addr = new TCSocketAddress(TCSocketAddress.WILDCARD_ADDR, port);
37
38     ProtocolAdaptorFactory factory = new ProtocolAdaptorFactory() {
39       public TCProtocolAdaptor getInstance() {
40         GenericProtocolAdaptor rv = new GenericProtocolAdaptor(sink);
41         return rv;
42       }
43     };
44
45     lsnr = connMgr.createListener(addr, factory, 4096, true);
46   }
47
48   public TCSocketAddress getServerAddr() {
49     return lsnr.getBindSocketAddress();
50   }
51
52   public void stop() {
53     if (lsnr != null) {
54       lsnr.stop();
55     }
56
57     connMgr.shutdown();
58   }
59
60   private static void usage() {
61     System.err.println("usage: SimpleServer <port> <verify>");
62     System.exit(1);
63   }
64
65   public static void main(String JavaDoc args[]) throws Exception JavaDoc {
66     if (args.length > 2) {
67       usage();
68     }
69
70     int p = 0;
71     boolean verify = false;
72
73     if (args.length > 0) {
74       p = Integer.parseInt(args[0]);
75     }
76
77     if (args.length > 1) {
78       verify = Boolean.valueOf(args[1]).booleanValue();
79     }
80
81     SimpleServer server = new SimpleServer(new EchoSink(verify), p);
82     server.start();
83     System.out.println("Server started at: " + server.getServerAddr());
84
85     Thread.sleep(Long.MAX_VALUE);
86   }
87
88 }
Popular Tags