This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

VerySimpleChatServer.java

By: a guest on Jun 27th, 2012  |  syntax: Java  |  size: 2.09 KB  |  views: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package ChatServer;
  2. import java.io.*;
  3. import java.net.*;
  4. import java.util.*;
  5.  
  6.  
  7. public class VerySimpleChatServer
  8. {
  9.     ArrayList clientOutputStreams;
  10.    
  11.     public class ClientHandler implements Runnable {
  12.         BufferedReader reader;
  13.         Socket sock;
  14.        
  15.         public ClientHandler(Socket clientSocket) {
  16.             try {
  17.                 sock = clientSocket;
  18.                 InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
  19.                 reader = new BufferedReader(isReader);
  20.                
  21.             }
  22.          //  
  23.  
  24.             catch (Exception ex) { ex.printStackTrace(); }
  25.         }
  26.        
  27.         public void run() {
  28.             String message;
  29.             try {
  30.                 while ((message = reader.readLine()) != null) {
  31.                     System.out.println("read " + message);
  32.                     tellEveryone(message);
  33.                 }
  34.             } catch (Exception ex) { ex.printStackTrace(); }
  35.         }
  36.     }
  37.    
  38.     public static void main(String[] args) {
  39.         new VerySimpleChatServer().go();
  40.     }
  41.    
  42.     public void go() {
  43.         clientOutputStreams = new ArrayList();
  44.         try {
  45.             ServerSocket serverSock = new ServerSocket(5000);
  46.             while(true) {
  47.                 Socket clientSocket = serverSock.accept();
  48.                 PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
  49.                 clientOutputStreams.add(writer);
  50.                
  51.                 Thread t = new Thread(new ClientHandler(clientSocket));
  52.                 t.start();
  53.                 System.out.println("got a connection");
  54.             }
  55.         } catch (Exception ex) { ex.printStackTrace(); }
  56.     }
  57.    
  58.     public void tellEveryone(String message) {
  59.         Iterator it = clientOutputStreams.iterator();
  60.         while (it.hasNext()) {
  61.             try {
  62.                 PrintWriter writer = (PrintWriter) it.next();
  63.                 writer.println(message);
  64.                 writer.flush();
  65.             } catch (Exception ex) { ex.printStackTrace(); }
  66.         }
  67.     }
  68. }
clone this paste RAW Paste Data