The entire Server code in all its Glory!



import java.io.*;
import java.net.*;
import java.util.*;

public class Server {

 ArrayList clientOutputStreams;

 //String[] output;

 public class ClientHandler implements Runnable{

 BufferedReader reader;
 Socket sock;

 //constructor
 public ClientHandler(Socket clientSocket){

 try{
 sock = clientSocket;
 InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
 reader = new BufferedReader(isReader);
 }catch(Exception ex){
 ex.printStackTrace();
 }
 }

 public void run(){
 String message;
 try{

 while((message = reader.readLine()) != null){
 System.out.println("Read " + message);
 tellEveryone(message);
 }
 }catch(Exception e){
 e.printStackTrace();
 }
 }

 }


 public void go(){
 clientOutputStreams = new ArrayList();


 try{
 ServerSocket serverSock = new ServerSocket(5000);

 while(true){
 Socket clientSocket = serverSock.accept();
 PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
 clientOutputStreams.add(writer);
 //writer.println(clientOutputStreams);
 Thread t = new Thread(new ClientHandler(clientSocket));
 t.start();
 System.out.println("Got a connection!");
 }

 }catch(Exception exx){
 exx.printStackTrace();
 }
 }

 public void tellEveryone(String messages){
 Iterator it = clientOutputStreams.iterator();
 while(it.hasNext()){

 try{

 PrintWriter writer = (PrintWriter) it.next();
 writer.println(messages);
 writer.flush();
 }catch(Exception e){
 e.printStackTrace();
 }
 }
 }

 public static void main(String[] args){
 new Server().go();
 }

}

Advertisements
The entire Server code in all its Glory!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s