-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMusicServer.java
85 lines (66 loc) · 1.78 KB
/
MusicServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package BeatBox;
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 {
this.clientSocket = socket;
this.in = new ObjectInputStream(this.clientSocket.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
Object o1 = null;
Object o2 = null;
try {
while((o1 = in.readObject()) != null){
o2 = in.readObject();
System.out.println("read two objects");
tellEveryone(o1,o2);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void go() {
this.clientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSock = new ServerSocket(4242);
System.out.println("Server Started");
while (true) {
Socket clientSocket = serverSock.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
this.clientOutputStreams.add(out);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void tellEveryone(Object one, Object two) {
Iterator<ObjectOutputStream> it = this.clientOutputStreams.iterator();
while (it.hasNext()) {
try {
ObjectOutputStream out = it.next();
out.writeObject(one);
out.writeObject(two);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}