01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.net.core;
06:
07: import com.tc.net.TCSocketAddress;
08: import com.tc.net.protocol.EchoSink;
09: import com.tc.net.protocol.GenericNetworkMessageSink;
10: import com.tc.net.protocol.GenericProtocolAdaptor;
11: import com.tc.net.protocol.ProtocolAdaptorFactory;
12: import com.tc.net.protocol.TCProtocolAdaptor;
13:
14: import java.io.IOException;
15:
16: /**
17: * A simple server instance that accepts GenericNetwork messages and delivers them to a sink
18: *
19: * @author teck
20: */
21: public class SimpleServer {
22: final GenericNetworkMessageSink sink;
23: TCConnectionManager connMgr = new TCConnectionManagerJDK14();
24: TCListener lsnr;
25: final int port;
26:
27: public SimpleServer(GenericNetworkMessageSink sink) {
28: this (sink, 0);
29: }
30:
31: public SimpleServer(GenericNetworkMessageSink sink, int port) {
32: this .sink = sink;
33: this .port = port;
34: }
35:
36: public void start() throws IOException {
37: TCSocketAddress addr = new TCSocketAddress(
38: TCSocketAddress.WILDCARD_ADDR, port);
39:
40: ProtocolAdaptorFactory factory = new ProtocolAdaptorFactory() {
41: public TCProtocolAdaptor getInstance() {
42: GenericProtocolAdaptor rv = new GenericProtocolAdaptor(
43: sink);
44: return rv;
45: }
46: };
47:
48: lsnr = connMgr.createListener(addr, factory, 4096, true);
49: }
50:
51: public TCSocketAddress getServerAddr() {
52: return lsnr.getBindSocketAddress();
53: }
54:
55: public void stop() {
56: if (lsnr != null) {
57: lsnr.stop();
58: }
59:
60: connMgr.shutdown();
61: }
62:
63: private static void usage() {
64: System.err.println("usage: SimpleServer <port> <verify>");
65: System.exit(1);
66: }
67:
68: public static void main(String args[]) throws Exception {
69: if (args.length > 2) {
70: usage();
71: }
72:
73: int p = 0;
74: boolean verify = false;
75:
76: if (args.length > 0) {
77: p = Integer.parseInt(args[0]);
78: }
79:
80: if (args.length > 1) {
81: verify = Boolean.valueOf(args[1]).booleanValue();
82: }
83:
84: SimpleServer server = new SimpleServer(new EchoSink(verify), p);
85: server.start();
86: System.out.println("Server started at: "
87: + server.getServerAddr());
88:
89: Thread.sleep(Long.MAX_VALUE);
90: }
91:
92: }
|