-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSessionManager.java
74 lines (64 loc) · 2.5 KB
/
SessionManager.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
import java.io.*;
import java.net.*;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
// SessionManager
// * main server
//
// * watch all connection trials
//
// * own session instance list
//
// * if connected, create new session in new thread & append to sessionList
//
// * if one session got changed => notify this change for all sessions
public class SessionManager {
public static final int PORT = 8080; // FIXME: port num
private static ArrayList<Session> sessionList = new ArrayList<>();
private static String model = "";
private static void logging(String context) {
System.out.println("[SessionManager] " + context);
}
public static void deleteSession(Session removeTarget) {
boolean removed = sessionList.remove(removeTarget);
if (removed) {
SessionManager.logging("successfully deleted session: " + removeTarget);
} else {
SessionManager.logging("failed to remove session from the session list");
}
}
public synchronized static void updateText(String newText) {
Model.updateModel(newText);
notifyChangesToAllSession();
}
// HACK: make clean
private static void notifyChangesToAllSession() {
// TODO 各SessionにModelが変わったことを通知する。
for (Session session : sessionList) {
try {
session.sendMessageToClient(Model.outputModel());
} catch (UnsupportedEncodingException e) {
SessionManager.logging("Err: " + e);
} catch (IOException e) {
SessionManager.logging("Err: " + e);
}
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
SessionManager.logging("Server launched at " + serverSocket);
try {
// TODO:
// ここ怪しい。Ctrl-Cとかで強制終了した時にちゃんとServerSocket.close()が呼ばれるかとか知らずに書いてる。
while (true) {
Socket socket = serverSocket.accept();
SessionManager.logging("Connection accepted: " + socket);
Session newSession = new Session(socket, /* id= */ SessionManager.sessionList.size());
sessionList.add(newSession);
newSession.sendMessageToClient(Model.outputModel());
}
} finally {
serverSocket.close();
}
}
}