/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.net.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.server.RMISocketFactory;
import java.util.Random;

final class Server {
    private static int connectionCnt;

    static class Work implements Runnable {
        private final Socket socket;

        Work(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            Random random = new Random();
            try {
                int data;
                InputStream is = socket.getInputStream();
                do {
                    data = is.read();
                } while (data != -1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            --connectionCnt;
            System.out.print("Connections: " + connectionCnt + '\r');
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket =
            RMISocketFactory.getDefaultSocketFactory().createServerSocket(9090);
        do {
            Socket socket = serverSocket.accept();
            ++connectionCnt;
            System.out.print("Connections: " + connectionCnt + '\r');
            new Thread(new Work(socket)).start();
        } while (true);
    }
}
