Created
March 7, 2013 15:51
-
-
Save rihenperry/5109015 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
import java.util.*; | |
public class MusicServer { | |
ArrayList<ObjectOutputStream> clientOutputStreams; | |
public static void main (String[] args) { | |
new MusicServer().go(); | |
} | |
public class ClientHandler implements Runnable { | |
ObjectInputStream in; | |
Socket clientSocket; | |
public ClientHandler(Socket socket) { | |
try { | |
clientSocket = socket; | |
in = new ObjectInputStream(clientSocket.getInputStream()); | |
} catch(Exception ex) {ex.printStackTrace();} | |
} // close constructor | |
public void run() { | |
Object o2 = null; | |
Object o1 = null; | |
try { | |
while ((o1 = in.readObject()) != null) { | |
o2 = in.readObject(); | |
System.out.println("read two objects"); | |
tellEveryone(o1, o2); | |
} // close while | |
} catch(Exception ex) {ex.printStackTrace();} | |
} // close run | |
} // close inner class | |
public void go() { | |
clientOutputStreams = new ArrayList<ObjectOutputStream>(); | |
try { | |
ServerSocket serverSock = new ServerSocket(4242); | |
while(true) { | |
Socket clientSocket = serverSock.accept(); | |
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream()); | |
clientOutputStreams.add(out); | |
Thread t = new Thread(new ClientHandler(clientSocket)); | |
t.start(); | |
System.out.println("got a connection"); | |
} | |
// now if I get here I have a connection | |
}catch(Exception ex) { | |
ex.printStackTrace(); | |
} | |
} | |
public void tellEveryone(Object one, Object two) { | |
Iterator it = clientOutputStreams.iterator(); | |
while(it.hasNext()) { | |
try { | |
ObjectOutputStream out = (ObjectOutputStream) it.next(); | |
out.writeObject(one); | |
out.writeObject(two); | |
}catch(Exception ex) {ex.printStackTrace();} | |
} | |
} // close tellEveryone | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment