|
| 1 | +import java.io.*; |
| 2 | +import java.net.*; |
| 3 | +import java.awt.*; |
| 4 | +import java.awt.event.*; |
| 5 | + |
| 6 | +import javax.swing.*; |
| 7 | + |
| 8 | +public class Client extends JFrame{ |
| 9 | + |
| 10 | + private JTextField userText; |
| 11 | + private JTextArea chatWindow; |
| 12 | + private ObjectOutputStream output; |
| 13 | + private ObjectInputStream input; |
| 14 | + private String message = ""; |
| 15 | + private String serverIP; |
| 16 | + private Socket connection; |
| 17 | + |
| 18 | + //constructor |
| 19 | + public Client(String host){ |
| 20 | + super("Client"); |
| 21 | + serverIP = host; |
| 22 | + userText = new JTextField(); |
| 23 | + userText.setEditable(false); |
| 24 | + userText.addActionListener( |
| 25 | + new ActionListener(){ |
| 26 | + public void actionPerformed(ActionEvent event){ |
| 27 | + sendMessage(event.getActionCommand()); |
| 28 | + userText.setText(""); |
| 29 | + } |
| 30 | + } |
| 31 | + ); |
| 32 | + add(userText, BorderLayout.NORTH); |
| 33 | + chatWindow = new JTextArea(); |
| 34 | + add(new JScrollPane(chatWindow)); |
| 35 | + setSize(300, 150); //Sets the window size |
| 36 | + setVisible(true); |
| 37 | + } |
| 38 | + |
| 39 | + //connect to server |
| 40 | + public void startRunning(){ |
| 41 | + try{ |
| 42 | + connectToServer(); |
| 43 | + setupStreams(); |
| 44 | + whileChatting(); |
| 45 | + }catch(EOFException eofException){ |
| 46 | + showMessage("\n Client terminated the connection"); |
| 47 | + }catch(IOException ioException){ |
| 48 | + ioException.printStackTrace(); |
| 49 | + }finally{ |
| 50 | + closeConnection(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + //connect to server |
| 55 | + private void connectToServer() throws IOException{ |
| 56 | + showMessage("Attempting connection... \n"); |
| 57 | + connection = new Socket(InetAddress.getByName(serverIP), 6789); |
| 58 | + showMessage("Connection Established! Connected to: " + connection.getInetAddress().getHostName()); |
| 59 | + } |
| 60 | + |
| 61 | + //set up streams |
| 62 | + private void setupStreams() throws IOException{ |
| 63 | + output = new ObjectOutputStream(connection.getOutputStream()); |
| 64 | + output.flush(); |
| 65 | + input = new ObjectInputStream(connection.getInputStream()); |
| 66 | + showMessage("\n The streams are now set up! \n"); |
| 67 | + } |
| 68 | + |
| 69 | + //while chatting with server |
| 70 | + private void whileChatting() throws IOException{ |
| 71 | + ableToType(true); |
| 72 | + do{ |
| 73 | + try{ |
| 74 | + message = (String) input.readObject(); |
| 75 | + showMessage("\n" + message); |
| 76 | + }catch(ClassNotFoundException classNotFoundException){ |
| 77 | + showMessage("Unknown data received!"); |
| 78 | + } |
| 79 | + }while(!message.equals("SERVER - END")); |
| 80 | + |
| 81 | + } |
| 82 | +} |
0 commit comments