Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.90 KB | None | 0 0
  1. Server:
  2. public class Server {
  3.  
  4.     private static final int PORT = 9001;
  5.  
  6.     private static HashSet<String> names = new HashSet<String>();
  7.     private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
  8.     public static void main(String[] args) throws Exception {
  9.  
  10.         ServerSocket listener = new ServerSocket(PORT);
  11.         System.out.println("The chat server is running. PORT = " + listener.getLocalPort());
  12.         try {
  13.             while (true) {
  14.                 new Handler(listener.accept()).start();
  15.             }
  16.         } finally {
  17.             listener.close();
  18.         }
  19.     }
  20.  
  21.     private static class Handler extends Thread {
  22.         private String name;
  23.         private Socket socket;
  24.         private BufferedReader in;
  25.         private PrintWriter out;
  26.  
  27.         public Handler(Socket socket) {
  28.             this.socket = socket;
  29.         }
  30.  
  31.         public void run() {
  32.             try {
  33.  
  34.                 in = new BufferedReader(new InputStreamReader(
  35.                         socket.getInputStream()));
  36.                 out = new PrintWriter(socket.getOutputStream(), true);
  37.  
  38.                 while (true) {
  39.                     out.println("SUBMITNAME");
  40.                     name = in.readLine();
  41.  
  42.                     if (name == null) {
  43.                         return;
  44.                     }
  45.                     synchronized (names) {
  46.                         if (!names.contains(name)) {
  47.                             names.add(name);
  48.  
  49.                             System.out.println(name + " has joined the chat!" + socket.getInetAddress().getHostAddress());
  50.                             out.println("NAMEACCEPTED");
  51.                             writers.add(out);
  52.                             for (PrintWriter writer : writers) {
  53.                                 writer.println("MESSAGE " + name + " has joined the chat!");
  54.                             }
  55.                             break;
  56.                         } else {
  57.                             writers.add(out);
  58.                             out.println("NAMEACCEPTED");
  59.                         }
  60.                     }
  61.                 }
  62.  
  63.  
  64.                 while (true) {
  65.                     String input = in.readLine();
  66.                     if (input == null) {
  67.                         return;
  68.                     }
  69.                     for (PrintWriter writer : writers) {
  70.                         writer.println("MESSAGE " + name + ": " + input);
  71.                     }
  72.  
  73.                 }
  74.             } catch (IOException e) {
  75.                 System.out.println(e);
  76.             } finally {
  77.                 // This client is going down!  Remove its name and its print
  78.                 // writer from the sets, and close its socket.
  79.                 if (name != null) {
  80.                     names.remove(name);
  81.                 }
  82.                 if (out != null) {
  83.                     writers.remove(out);
  84.                 }
  85.                 System.out.println(name + " has left the chat!");
  86.                 for (PrintWriter writer : writers) {
  87.                     writer.println("MESSAGE " + name + " has left the chat!");
  88.                 }
  89.                 try {
  90.                     socket.close();
  91.                 } catch (IOException e) {
  92.                 }
  93.             }
  94.         }
  95.     }
  96. }
  97.  
  98. Client:
  99.  
  100. public class Client {
  101.  
  102.     BufferedReader in;
  103.     PrintWriter out;
  104.     JFrame frame = new JFrame("Chatter");
  105.     JTextField textField = new JTextField(40);
  106.     JTextArea messageArea = new JTextArea(8, 40);
  107.  
  108.     public Client() {
  109.  
  110.         // Layout GUI
  111.         textField.setEditable(false);
  112.         messageArea.setEditable(false);
  113.         frame.getContentPane().add(textField, "North");
  114.         frame.getContentPane().add(new JScrollPane(messageArea), "Center");
  115.         frame.pack();
  116.  
  117.         // Add Listeners
  118.         textField.addActionListener(new ActionListener() {
  119.            
  120.             public void actionPerformed(ActionEvent e) {
  121.                 out.println(textField.getText());
  122.                 textField.setText("");
  123.             }
  124.         });
  125.     }
  126.  
  127.     /**
  128.      * Prompt for and return the address of the server.
  129.      */
  130.     private String getServerAddress() {
  131.         return JOptionPane.showInputDialog(
  132.             frame,
  133.             "Enter IP Address of the Server:",
  134.             "Welcome to the Chatter",
  135.             JOptionPane.QUESTION_MESSAGE);
  136.     }
  137.  
  138.     /**
  139.      * Prompt for and return the desired screen name.
  140.      */
  141.     private String getName() {
  142.         return JOptionPane.showInputDialog(
  143.             frame,
  144.             "Choose a screen name:",
  145.             "Screen name selection",
  146.             JOptionPane.PLAIN_MESSAGE);
  147.     }
  148.  
  149.     /**
  150.      * Connects to the server then enters the processing loop.
  151.      */
  152.     private void run() throws IOException {
  153.  
  154.         // Make connection and initialize streams
  155.         String serverAddress = getServerAddress();
  156.         Socket socket = new Socket(serverAddress, 9001);
  157.         in = new BufferedReader(new InputStreamReader(
  158.             socket.getInputStream()));
  159.         out = new PrintWriter(socket.getOutputStream(), true);
  160.  
  161.         // Process all messages from server, according to the protocol.
  162.         while (true) {
  163.             String line = in.readLine();
  164.             if (line.startsWith("SUBMITNAME")) {
  165.                 out.println(getName());
  166.             } else if (line.startsWith("NAMEACCEPTED")) {
  167.                 textField.setEditable(true);
  168.             } else if (line.startsWith("MESSAGE")) {
  169.                 messageArea.append(line.substring(8) + "\n");
  170.             }
  171.         }
  172.     }
  173.  
  174.     /**
  175.      * Runs the client as an application with a closeable frame.
  176.      */
  177.     public static void main(String[] args) throws Exception {
  178.         Client client = new Client();
  179.         client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  180.         client.frame.setVisible(true);
  181.         client.run();
  182.     }
  183. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement