Advertisement
tilahun1

Untitled

Jul 2nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. package chatClientServer;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.net.*;
  5. import javax.swing.*;
  6.  
  7.  
  8. public class ChatClient {
  9.  
  10.     BufferedReader in;
  11.     PrintWriter out;
  12.     JFrame frame = new JFrame("Chatter");
  13.     JTextField textField = new JTextField(40);
  14.     JTextArea messageArea = new JTextArea(8, 40);
  15.  
  16.     public ChatClient() {
  17.  
  18.    
  19.         textField.setEditable(false);
  20.         messageArea.setEditable(false);
  21.         frame.getContentPane().add(textField, "North");
  22.         frame.getContentPane().add(new JScrollPane(messageArea), "Center");
  23.         frame.pack();
  24.  
  25.        
  26.         textField.addActionListener(new ActionListener() {
  27.  
  28.             public void actionPerformed(ActionEvent e) {
  29.                 out.println(textField.getText());
  30.                 textField.setText("");
  31.             }
  32.         });
  33.     }
  34.  
  35.  
  36.     private String getServerAddress() {
  37.         return JOptionPane.showInputDialog(frame,
  38.                 "Enter IP Address of the Server:", "Welcome to the Chatter",
  39.                 JOptionPane.QUESTION_MESSAGE);
  40.     }
  41.  
  42.     private String getName() {
  43.         return JOptionPane.showInputDialog(frame, "Choose a screen name:",
  44.                 "Screen name selection", JOptionPane.PLAIN_MESSAGE);
  45.     }
  46.  
  47.     private void run() throws IOException {
  48.  
  49.         String serverAddress = getServerAddress();
  50.         Socket socket = new Socket(serverAddress, 9001);
  51.         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  52.         out = new PrintWriter(socket.getOutputStream(), true);
  53.  
  54.         while (true) {
  55.             String line = in.readLine();
  56.             if (line.startsWith("SUBMITNAME")) {
  57.                 out.println(getName());
  58.             } else if (line.startsWith("NAMEACCEPTED")) {
  59.                 textField.setEditable(true);
  60.             } else if (line.startsWith("MESSAGE")) {
  61.                 messageArea.append(line.substring(8) + "\n");
  62.             }
  63.         }
  64.     }
  65.  
  66.  
  67.     public static void main(String[] args) throws Exception {
  68.         ChatClient client = new ChatClient();
  69.         client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  70.         client.frame.setVisible(true);
  71.         client.run();
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement