package se.kth.isk.leffe.chat.client; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; /** * A non-multiplexing chat client. There is no need to use multiplexing here * since there are only two threads and both are always active. */ public class ChatClient { private static final int SERVER_PORT = 4711; private static final String SERVER = "localhost"; private Socket server; /** * Constructs a chat client andconnects to a chat server. */ public ChatClient() throws IOException { server = new Socket(SERVER, SERVER_PORT); } /** * Starts one thread that echos input from the server to System.out and * another that echos input from System.in to the server. * * The Reader/Writer API is used instead of channels because its easier * way of converting between bytes and Strings is sufficient. */ public void chat() { listenToServer(); sendToServer(); } private void listenToServer() { Runnable listener = new Runnable() { public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); while (true) { System.out.println(in.readLine()); } } catch (IOException ioe) { ioe.printStackTrace(); } } }; new Thread(listener).start(); } private void sendToServer() { Runnable sender = new Runnable() { public void run() { try { PrintStream out = new PrintStream(server.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { out.println(in.readLine()); } } catch (IOException ioe) { ioe.printStackTrace(); } } }; new Thread(sender).start(); } public static void main(String[] args) { try { new ChatClient().chat(); } catch (IOException ioe) { ioe.printStackTrace(); } } }