-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServerThread.java
More file actions
96 lines (87 loc) · 3.27 KB
/
Copy pathChatServerThread.java
File metadata and controls
96 lines (87 loc) · 3.27 KB
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
86
87
88
89
90
91
92
93
94
95
96
package server;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import server.chatlog;
public class ChatServerThread extends Thread{
private String alias = null;
private Socket sock = null;
List<PrintWriter> listwriter = null;
public ChatServerThread(List<PrintWriter> listwriter, Socket sock){
this.sock = sock;
this.listwriter = listwriter;
}
public void run() {
try{
//Creating a reader and writer for socket's input and output streams
BufferedReader buffreader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8));
while(true){
// rendering request from buffer, 3 different paths QUIT,JOIN,MESSAGE
String request = buffreader.readLine();
if(request == null){
quit(printwriter);
chatlog.out("Client disconnected");
break;
}
chatlog.out(request);
String[] token = request.split(":");
if("join".equals(token[0])){
String joinedstring = String.join("", Arrays.copyOfRange(token, 1, token.length));
join(joinedstring,printwriter);
}
else if ("message".equals(token[0])){
String joinedstring = String.join("", Arrays.copyOfRange(token, 1, token.length));
message(joinedstring);
}
else if("quit".equals(token[0])){
quit(printwriter);
}
}
}
catch(Exception e){
chatlog.out(this.alias + "quit");
}
}
// QUIT: remove writer from list and broadcast client quit
private void quit(PrintWriter writer){
removeWriter(writer);
String msg = this.alias + "quit";
broadcast(msg);
}
private void removeWriter(PrintWriter writer){
synchronized(listwriter){
listwriter.remove(writer);
}
}
// JOIN: Broadcast user joined and add user to list of Printwriter
private void join(String alias, PrintWriter writer){
this.alias = alias;
String msg = alias +"joined";
broadcast(msg);
addwriter(writer);
}
private void message(String msg){
broadcast(this.alias +":" +msg);
}
// addwriter: mutex lock on list to add writer
private void addwriter(PrintWriter writer){
synchronized(listwriter){
listwriter.add(writer);
}
}
// broadcast: thread takes control of list and updates
private void broadcast(String msg){
synchronized(listwriter){
for(PrintWriter writer : listwriter){
writer.println(msg);
writer.flush();
}
}
}
}