|
| 1 | + |
| 2 | +import java.awt.*; |
| 3 | +import java.awt.event.*; |
| 4 | +import java.io.*; |
| 5 | +import java.net.*; |
| 6 | +import javax.swing.*; |
| 7 | + |
| 8 | +public class Client implements ActionListener { |
| 9 | + |
| 10 | + JTextArea tArea = new JTextArea(); |
| 11 | + JTextField tField = new JTextField(10); |
| 12 | + JLabel status = new JLabel("Waiting for server"); |
| 13 | + PrintWriter out; |
| 14 | + BufferedReader in; |
| 15 | + |
| 16 | + void createGUI() { |
| 17 | + JFrame frame = new JFrame("Chat - Client"); |
| 18 | + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
| 19 | + frame.setSize(400, 400); |
| 20 | + |
| 21 | + JPanel panel = new JPanel(); |
| 22 | + JButton btnSend = new JButton("Send"); |
| 23 | + btnSend.addActionListener(this); |
| 24 | + panel.add(new JLabel("Message")); |
| 25 | + panel.add(tField); |
| 26 | + panel.add(btnSend); |
| 27 | + |
| 28 | + frame.add(panel, BorderLayout.SOUTH); |
| 29 | + frame.add(new JLabel("Status: "), BorderLayout.NORTH); |
| 30 | + frame.add(status, BorderLayout.NORTH); |
| 31 | + frame.add(tArea, BorderLayout.CENTER); |
| 32 | + tArea.setEditable(false); |
| 33 | + frame.setVisible(true); |
| 34 | + } |
| 35 | + |
| 36 | + void connectToServer() { |
| 37 | + try { |
| 38 | + Socket socket = new Socket(InetAddress.getLocalHost(), 8000); |
| 39 | + out = new PrintWriter(socket.getOutputStream(), true); |
| 40 | + in = new BufferedReader( |
| 41 | + new InputStreamReader(socket.getInputStream())); |
| 42 | + status.setText("Server Connected"); |
| 43 | + while (true) { |
| 44 | + String str = in.readLine(); |
| 45 | + tArea.append(str + "\n"); |
| 46 | + } |
| 47 | + } catch (Exception exc) { |
| 48 | + System.out.println("No Server!"); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public void actionPerformed(ActionEvent event) { |
| 53 | + String message = tField.getText(); |
| 54 | + out.println(message); |
| 55 | + tField.setText(""); |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) { |
| 59 | + Client client = new Client(); |
| 60 | + client.createGUI(); |
| 61 | + client.connectToServer(); |
| 62 | + } |
| 63 | +} |
0 commit comments