// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package socket.plain.binary.traditional;

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

public class MultiServer {
    public static class ClientHandler extends Thread {
        private Socket s;
        public ClientHandler(Socket s) {
            this.s = s;
        }
        @Override
        public void run() {
            try {
                System.out.printf("(handler in thread %d)\n", Thread.currentThread().getId());
                // get streams
                DataInputStream dis = new DataInputStream(s.getInputStream());
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                // read a and b
                int a = dis.readInt();
                int b = dis.readInt();
                // calculate c and send
                int c = a + b;
                dos.writeInt(c);
                dos.flush();
                // read v
                int buflen = dis.readByte();
                byte[] buf = new byte[buflen];
                int ix = 0;
                while(ix < buf.length) {
                    ix += dis.read(buf, ix, buf.length - ix);
                }
                String v = new String(buf, "UTF-8");
                // calculate v2 and send
                String v2 = v + v;
                byte[] v2b = v2.getBytes("UTF-8");
                dos.writeByte(v2b.length);
                dos.write(v2b);
                dos.flush();
                // close connection
                dis.close();
                dos.close();
                s.close();
            } catch (IOException e) {
                // TODO
                e.printStackTrace();
            }
        }
    }
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // listen on port
            @SuppressWarnings("resource")
            ServerSocket ss = new ServerSocket(PORT);
            while(true) {
                // accept connection
                Socket s = ss.accept();
                System.out.printf("(connection from %s)\n", s.getRemoteSocketAddress());
                // start new thread to handle connection
                (new ClientHandler(s)).start();
            }
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
}
