Client
  import javax.swing.JFrame;
  import javax.swing.JTextField;
  import javax.swing.JTextArea;
  import javax.swing.JLabel;
  import java.awt.event.KeyAdapter;
  import java.awt.event.KeyEvent;
  import java.awt.event.WindowAdapter;
  import java.awt.event.WindowEvent;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.net.Socket;
  import java.net.SocketException;
  import java.net.UnknownHostException;
  public class ChatClient extends JFrame {
  JTextArea textArea;
  Socket socket;
  OutputStream oStream;
  PrintWriter pWriter;
  private JTextField textField;
  private boolean start;
  private BufferedReader bReader;
  public ChatClient() {
  getContentPane().setLayout(null);
  textArea = new JTextArea();
  textArea.setEditable(false);
  textArea.setBounds(10, 58, 414, 309);
  getContentPane().add(textArea);
  textField = new JTextField();
  textField.addKeyListener(new KeyAdapter() {
  @Override
  public void keyPressed(KeyEvent e) {
  if (e.getKeyChar() == KeyEvent.VK_ENTER) {
  String string = textField.getText();
  if (!string.equals("")) {
  textArea.append(string + " ");
  textField.setText("");
  pWriter.println(string);
  }
  }
  }
  });
  textField.setBounds(10, 377, 414, 21);
  getContentPane().add(textField);
  textField.setColumns(10);
  JLabel userName = new JLabel("userName");
  userName.setBounds(34, 33, 61, 15);
  getContentPane().add(userName);
  this.setSize(452, 446);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setVisible(true);
  this.addWindowListener(new WindowAdapter() {
  @Override
  public void windowClosing(WindowEvent e) {
  super.windowClosing(e);
  disconnect();
  System.exit(0);
  }
  });
  new Thread() {
  String mesString;
  boolean start = true;
  @Override
  public void run() {
  try {
  connect();
  while (start) {
  while ((mesString = bReader.readLine()) != null) {
  textArea.append(mesString + " ");
  }
  }
  } catch (SocketException e1) {
  } catch (IOException e) {
  e.printStackTrace();
  }
  };
  }.start();
  }
  public void connect() {
  try {
  socket = new Socket("127.0.0.1", 8888);
  oStream = socket.getOutputStream();
  pWriter = new PrintWriter(oStream, true);
  bReader = new BufferedReader(new InputStreamReader(
  socket.getInputStream()));
  } catch (UnknownHostException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  public void disconnect() {
  try {
  if (pWriter != null) {
  pWriter.close();
  }
  if (bReader != null) {
  bReader.close();
  }
  if (socket != null) {
  socket.close();
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  public static void main(String[] args) {
  new ChatClient();
  }
  }