PoolServerBase.java Source code

Java tutorial

Introduction

Here is the source code for PoolServerBase.java

Source

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class PoolServerBase extends Thread {
    protected Socket socket;

    static PoolServerBase head = null;

    protected PoolServerBase next = null;

    static protected boolean init(Class clobj, int threads) {
        try {
            for (int i = 0; i < threads; i++) {
                PoolServerBase thread = (PoolServerBase) clobj.newInstance();
                thread.next = head;
                head = thread;
                thread.start();
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    static synchronized protected void addToList(PoolServerBase me) {
        me.next = head;
        head = me;
    }

    synchronized protected void waitForSignal() {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }

    public void run() {
        while (true) {
            waitForSignal();
            doClientProcessing();
            addToList(this);
        }
    }

    synchronized protected void handleClient(Socket s) {
        socket = s;
        notify();
    }

    protected void doClientProcessing() {
        try {
            String s = "Server.";
            s += "Thread: " + this.toString();
            socket.getOutputStream().write(s.getBytes());
            sleep(10000); // simulate processing
            s = "Complete";
            socket.getOutputStream().write(s.getBytes());
            socket.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    static synchronized protected boolean listEmpty() {
        return head == null;
    }

    static protected void assignThread(Socket sock) {
        PoolServerBase t = head;
        head = head.next;
        t.socket = sock;
        synchronized (t) {
            t.notify();
        }
    }

    static public void startServer(int port) {
        ServerSocket ssock;
        Socket sock;
        try {
            ssock = new ServerSocket(port);
            while (true) {
                Socket esock = null;
                try {
                    esock = ssock.accept();
                    while (listEmpty())
                        yield();
                    assignThread(esock);
                } catch (Exception e) {
                    try {
                        esock.close();
                    } catch (Exception ec) {
                    }
                }
            }
        } catch (IOException e) {
        }
    }

    static public void main(String args[]) {
        init(PoolServerBase.class, 3);
        System.out.println("Starting server on port 808");
        startServer(808);
    }
}