// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("localhost", 12345);
            PrintWriter netpw = new PrintWriter(s.getOutputStream(), true);
            BufferedReader netbr = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter conpw = new PrintWriter(System.out, true);
            BufferedReader conbr = new BufferedReader(new InputStreamReader(System.in));
            ServerHandler srv = new ServerHandler(conpw, netbr);
            srv.start();
            netpw.println("LOGIN " + args[0]);
            String line;
            System.out.print("Indtast text (afslut med CTRL/Z): ");
            while((line = conbr.readLine()) != null) {
                netpw.println("SEND " + line);
                System.out.print("Indtast text (afslut med CTRL/Z): ");
            }
            netbr.close();
            netpw.close();
            s.close();
            srv.interrupt();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ServerHandler extends Thread {
    private BufferedReader br;
    private PrintWriter pw;
    public ServerHandler(PrintWriter pw, BufferedReader br) {
        this.pw = pw;
        this.br = br;
    }
    public void run() {
        try {
            String line;
            while((line = br.readLine()) != null) {
                pw.println(line);
            }
        } catch (IOException e) {
            // nothing
        }
    }
}
