EchoServer



EchoServer.java
import java.io.*;
import java.net.*;

/* EchoServerはクライアントからの接続を待ち、echp portを用いて受信したデータをそのまま送り返す */

class EchoServer extends Thread
{
    static final int ECHO_PORT = 7;
    Socket s;

    /* Constructor */
    EchoServer(Socket s) throws IOException
    {
        System.out.println("新しいクライアントからの接続がありました。");
        this.s = s; 
    }
    /* クライアントが接続を切るまで受信したデータをエコーする。*/

    public void run()
    {
        System.out.println("新しいスレッドの開始 socket:" + s);
        InputStream  in   = null;
        OutputStream out  = null;
        int count=0;

        try {
            in  = s.getInputStream();
            out = s.getOutputStream();
            byte[] b = new byte[16];
            int c;
            while ((c = in.read(b)) > 0) {
                out.write(b, 0, c);
                count++;
            }
            System.out.println("EOF:"+count+"bytes");
        }
        catch (IOException ioe) {
            System.out.println(ioe);
        }
        finally {
            try {
                System.out.println("接続を閉じます。\n");
                in.close();
                out.close();
                s.close();
            }
        catch (IOException i) {
            System.out.println(i);
        }
    }
}
/*******************************************************************
 *   main - サーバーのソケットを開き、このソケットがクライアントを *
 * 受け付けたらサーバーをスレッドとして動作させる。                *
 *******************************************************************/
    public static void main(String[] args)
    {
        System.out.println("EchoServer 開始...");
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(ECHO_PORT);
            while(true)
                (new EchoServer(serverSocket.accept())).start();
        }
        catch(Exception e){}
        finally {
            try {
                serverSocket.close();
            }
            catch (IOException i) {
                System.out.println(i);
            }
        }
    }
}