import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class Client extends JFrame implements Runnable { private Thread thread = new Thread(this); private boolean running = true; private Socket s = null; private PrintWriter out = null; private BufferedReader in = null; private static String host = "127.0.0.1"; private static int port = 2000; private JTextField textField = new JTextField(); private JTextArea textArea = new JTextArea(); public static void main(String args[]) { if(args.length != 0) { host = args[0]; if(args.length != 1) { port = Integer.parseInt(args[1]); } } new Client(); } public Client() { textField.addActionListener(new L2()); getContentPane().add("North", textField); getContentPane().add("Center", new JScrollPane(textArea)); setLocation(420, 0); setSize(400, 200); addWindowListener(new L1()); setVisible(true); try { s = new Socket(host, port); setTitle("CONNECTED TO: " + host + " - ON PORT: " + port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); } catch (IOException ioe) { System.out.println("COULD NOT CONNECT: "+ ioe); killMe(); } thread.start(); } public void run() { String inputLine = ""; while(running) { try { inputLine = in.readLine(); } catch(NullPointerException npe) { System.out.println("NullPointer generated: " + npe); System.out.println("Stopping client!"); running = false; killMe(); } catch(IOException ioe) { System.out.println("IOException generated: " + ioe); System.out.println("Stopping client!"); running = false; killMe(); } textArea.append(inputLine + "\n"); textArea.setCaretPosition(textArea.getText().length()); Toolkit.getDefaultToolkit().beep(); } } private void sendMessage(String message) { out.println(message); if(message.equals("exit")) killMe(); } private String getHost(Socket s) { try { return(s.getInetAddress().getLocalHost().getHostName()); } catch(UnknownHostException e) { return("unknown"); } } public void killMe() { running = false; dispose(); try { out.close(); in.close(); s.close(); } catch(IOException ioe) { System.out.println("IOException generated: " + ioe); } System.exit(1); } class L1 extends WindowAdapter { // Anropar inte killMe har sa jag kan testa osnygga avslut :-) public void windowClosing(WindowEvent we) { dispose(); } public void windowClosed(WindowEvent we) { System.exit(1); } } class L2 implements ActionListener { public void actionPerformed(ActionEvent ae) { sendMessage(textField.getText()); textField.setText(""); } } }