package yoonforh.generic; /* * Copyright (c) 1996 Yoon Kyung Koo. All Rights Reserved. * * GenericServer.java * Author: Yoon Kyung Koo (yoonforh@interpia.net, http://interpia.net/~yoonforh) * Date: 10/24/96 * VERSION HISTORY * Last Update: 10/31/97 * Version: 1.00 (for JDK 1.02 API) * added finally clause in run method * Update: 10/25/96 * Version: 0.99 (for JDK 1.02 API) */ import java.net.*; import java.io.*; import java.util.Vector; import java.util.Date; public class GenericServer { private final static int DEFAULT_PORT = 6561; private static int port = DEFAULT_PORT ; private ConnectionManager cm = null; // 연결을 관리하는 쓰레드 public static PrintStream log = null; public static void main(String args[]) { int next = 0; String arg; while (true) { try { arg = args[next++].toLowerCase(); if (arg.startsWith("-l")) // 로그 파일 지정 log = new PrintStream(new FileOutputStream(args[next++]), true); /* autoflush on */ else if (arg.startsWith("-p")) // 포트 번호 지정 port = Integer.parseInt(args[next++]); } catch (IOException i) { log = null; System.err.println("WARNING\tunable to create log file"); } catch (NumberFormatException n) { port = DEFAULT_PORT; System.err.println("WARNING\tbad port number, using 6561"); } catch (ArrayIndexOutOfBoundsException a) {break; } } new GenericServer(); } /* end main() */ GenericServer() { try { if (log == null) log = new PrintStream(System.out, true); log.println("GenericServer is initializing to port " + port); } catch (Exception i) {} cm = new ConnectionManager(port); // 접속을 관리하는 쓰레드 생성. cm.start(); // ConnectionManager의 run() 도구 호출 } } /* ConnectionManager는 접속을 기다리다가 클라이언트가 연결해오면 해당 클라이언트를 처리할 ServerConnection 쓰레드를 생성한다. 일종의 동기적인 멀티플렉싱이다. */ class ConnectionManager extends Thread { private static int port; private static Vector my_threads = new Vector(5,2); /* 초기치 5, 증가치 2인 벡터를 생성한다. 이 벡터에는 소켓이 연결되면 생성되는 ServerConnection 쓰레 드 인스턴스들이 저장된다. */ private ServerSocket main_socket = null; public ConnectionManager(int portNo) { port = portNo; } public void run() { serveRequests(); // 서버 소켓을 생성하여 무한 루프를 돌다가 클라이언트들이 접속해오면 연결을 생성하여 // 각각의 연결에 하나의 쓰레드를 만들어주는 루틴이다. } private void serveRequests() { try { main_socket = new ServerSocket(port); // 서버 소켓 생성 } catch(Exception e) { GenericServer.log.println("Exception ["+e+"] while binding to port ["+port+"]. exiting..."); System.exit(1); } ServerConnection temp_sc = null; while (true) // 무한 루프. 이 루프의 포트는 지정한 서버의 포트이다. { try { Socket this_connection = main_socket.accept(); // 서버 소켓이 클라이언트를 기다렸다가 연결을 생성한다. // accept()의 반환값은 Socket 인스턴스이고 앞으로 연결된 클라이언트와 // 대화는 이 인스턴스를 통해서 한다. temp_sc = new ServerConnection(this_connection); // 연결이 생성되면 이 Socket 인스턴스로 ServerConnection 쓰레드를 생성 GenericServer.log.println("new Server Connection created"); temp_sc.start(); // ServerConnection 인스턴스의 run() 호출 my_threads.addElement(temp_sc); // ServerConnection 인스턴스를 벡터에 추가 /* 벡터의 크기만큼 루프를 반복한다. 벡터에 저장되어 있는 각 ServerConnection 쓰레드가 실행 중인지 검사하고 쓰레드가 종료하였으면 벡터에서 제거한다. ServerConnection 쓰레드는 소켓을 종료하면 실행을 중단한다. */ for(int i=0; i