这是一个非常好的Socket服务器样板程序,这个socket服务器可以为你建立指定的监听端口、客户端请求响应机制等一些服务器所具备的基本框架
/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */
import java.io.*; import java.net.*; import java.util.*;
/** * This class is a generic framework for a flexible, multi-threaded server. * It listens on any number of specified ports, and, when it receives a * connection on a port, passes input and output streams to a specified Service * object which provides the actual service. It can limit the number of * concurrent connections, and logs activity to a specified stream. **/ public class Server { /** * A main() method for running the server as a standalone program. The * command-line arguments to the program should be pairs of servicenames * and port numbers. For each pair, the program will dynamically load the * named Service class, instantiate it, and tell the server to provide * that Service on the specified port. The special -control argument * should be followed by a password and port, and will start special * server control service running on the specified port, protected by the * specified password. **/ public static void main(String[] args) { try { if (args.length < 2) // Check number of arguments throw new IllegalArgumentException("Must specify a service"); // Create a Server object that uses standard out as its log and // has a limit of ten concurrent connections at once. Server s = new Server(System.out, 10);
// Parse the argument list int i = 0; while(i < args.length) { if (args[i].equals("-control")) { // Handle the -control arg i++; String password = args[i++]; int port = Integer.parseInt(args[i++]); // add control service s.addService(new Control(s, password), port); } else { // Otherwise start a named service on the specified port. // Dynamically load and instantiate a Service class String serviceName = args[i++]; Class serviceClass = Class.forName(serviceName); Service service = (Service)serviceClass.newInstance(); int port = Integer.parseInt(args[i++]); s.addService(service, port); } } } catch (Exception e) { // Display a message if anything goes wrong System.err.println("Server: " + e); System.err.println("Usage: java Server " + "[-control[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一页
|