import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

class ChatServer {
   static ServerSocket s;
   static Socket sck;
   static DataInputStream input;
   static DataOutputStream output;
   static JFrame window;
   static JTextArea display;
   static JTextField chatBox;
   static JTextField id;
   static int number;
   static String speakerName;

   public static void main(String args[]) {
      speakerName = "Server";
      System.out.println("Awaiting client socket connection...");
      try {
         ServerSocket s = new ServerSocket(8007);
         Socket sck = s.accept();
         input = new DataInputStream(sck.getInputStream());
         output = new DataOutputStream(sck.getOutputStream());
      }
      catch(IOException exc) { }
      System.out.println("Socket connection established.");

      display = new JTextArea();
      display.setRows(5);
      display.setEditable(false);
      
      id = new JTextField();
      id.setEditable(false);
      
      chatBox = new JTextField();
      chatBox.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent i) {
            if (i.getKeyCode()==KeyEvent.VK_ENTER) {
               try {
                  String line = speakerName+": "+chatBox.getText()+"\n";
                  output.writeUTF(line);
                  display.insert(line,0);
                  chatBox.setText("");
               }
               catch(IOException e) {}
            }
         }
      });

      window = new JFrame();
      window.setTitle("Java Swing Chat Server");
      window.setBounds(100,100,320,240);
      window.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.out.println("Socket connection closed.");
            System.exit(1);
         }
      });

      JPanel chatInputPanel = new JPanel(new BorderLayout());
      chatInputPanel.add(chatBox,BorderLayout.CENTER);
      JScrollPane displayScrollPane = new JScrollPane(display);
      JPanel chatPanel = new JPanel(new BorderLayout());
      chatPanel.add(displayScrollPane,BorderLayout.SOUTH);
      chatPanel.add(chatInputPanel,BorderLayout.NORTH);

      window.getContentPane().add(chatPanel,BorderLayout.SOUTH);
      window.getContentPane().add(id,BorderLayout.NORTH);
      window.setVisible(true);
      id.setText("You are: "+speakerName);

      while(true) {
         try {
            String ss = input.readUTF();
            display.insert(ss,0);
         } catch(IOException e) {}
      }
   }
}
