import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; import java.net.*; public class Client extends JFrame implements Runnable{ private JTextField textField = null; private JTextArea textArea = null; private BufferedReader in = null; private PrintWriter out = null; private Socket socket = null; private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 2000; public Client(String host, int port){ super(); textField = new JTextField(); textArea = new JTextArea(); textArea.setEditable(false); textField.addKeyListener(new ReturnListener()); addWindowListener(new CloseListener()); getContentPane().add(textField, BorderLayout.SOUTH); getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); setSize(400, 200); show(); makeConnection(host, port); } public void makeConnection(String host, int port){ try{ socket = new Socket(host, port); setTitle("CONNECTED TO: " + host + " - ON PORT: " + port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); (new Thread(this)).start(); }catch(ConnectException ce){ textArea.append("Can't connect to server!"); }catch(UnknownHostException uhe){ textArea.append("Unknown host!"); }catch(IOException ioe){ textArea.append("Error!"); } } public void run(){ String msg = null; try{ while ((msg = in.readLine()) != null){ textArea.append(msg + "\n"); textArea.setCaretPosition(textArea.getText().length()); } textArea.append("-------------------------------------------\n" + "Connection to the server was broken,\nplease close this client!"); }catch(IOException ioe){ textArea.append("-------------------------------------------\n" + "Connection to the server was broken,\nplease close this client!"); } } class ReturnListener extends KeyAdapter{ public void keyPressed(KeyEvent e){ if (e.getKeyCode() == e.VK_ENTER){ out.println(textField.getText()); out.flush(); textField.setText(""); textArea.setCaretPosition(textArea.getText().length()); } } } public class CloseListener extends WindowAdapter{ public void windowClosing(WindowEvent e){ try{ out.close(); in.close(); socket.close(); }catch(Exception ioe){ System.out.println(ioe); System.exit(0); } System.exit(0); } } public static void main(String[] args){ if (args.length == 0){ new Client(DEFAULT_HOST , DEFAULT_PORT); }else if (args.length == 1){ new Client(args[0] , DEFAULT_PORT); }else if (args.length == 2){ try{ new Client(args[0] , Integer.parseInt(args[1])); }catch(NumberFormatException nfe){ System.out.println("USAGE: java Client "); } } else System.out.println("USAGE: java Client "); } }