-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
53 lines (46 loc) · 1.38 KB
/
Server.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
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Server {
private ArrayList<Connection> clientConnections;
private ServerSocket serverSocket;
private ExecutorService connectionThreadPool;
private boolean running;
public Server() {
clientConnections = new ArrayList<>();
running = true;
}
public void listen(int port) throws IOException {
serverSocket = new ServerSocket(port);
connectionThreadPool = Executors.newCachedThreadPool();
while(running) {
Socket connectionSocket = serverSocket.accept();
Connection clientConnection = new Connection(this, connectionSocket);
clientConnections.add(clientConnection);
connectionThreadPool.execute(clientConnection);
}
}
public void broadcast(String message) {
for(Connection connection : clientConnections) {
if(connection != null) {
connection.sendMessage(message);
}
}
}
public void close() {
try {
running = false;
if(!serverSocket.isClosed()) {
serverSocket.close();
}
for(Connection connection : clientConnections) {
connection.close();
}
} catch(Exception e) {
System.out.println("Error occured closing server: " + e);
}
}
}