-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathChatServer.java
More file actions
95 lines (92 loc) · 2.3 KB
/
ChatServer.java
File metadata and controls
95 lines (92 loc) · 2.3 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
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer {
public static void main(String[] args) {
try{
ServerSocket server = new ServerSocket(10001);
System.out.println("Waiting connection...");
HashMap hm = new HashMap();
while(true){
Socket sock = server.accept();
ChatThread chatthread = new ChatThread(sock, hm);
chatthread.start();
} // while
}catch(Exception e){
System.out.println(e);
}
} // main
}
class ChatThread extends Thread{
private Socket sock;
private String id;
private BufferedReader br;
private HashMap hm;
private boolean initFlag = false;
public ChatThread(Socket sock, HashMap hm){
this.sock = sock;
this.hm = hm;
try{
PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
id = br.readLine();
broadcast(id + " entered.");
System.out.println("[Server] User (" + id + ") entered.");
synchronized(hm){
hm.put(this.id, pw);
}
initFlag = true;
}catch(Exception ex){
System.out.println(ex);
}
} // construcor
public void run(){
try{
String line = null;
while((line = br.readLine()) != null){
if(line.equals("/quit"))
break;
if(line.indexOf("/to ") == 0){
sendmsg(line);
}else
broadcast(id + " : " + line);
}
}catch(Exception ex){
System.out.println(ex);
}finally{
synchronized(hm){
hm.remove(id);
}
broadcast(id + " exited.");
try{
if(sock != null)
sock.close();
}catch(Exception ex){}
}
} // run
public void sendmsg(String msg){
int start = msg.indexOf(" ") +1;
int end = msg.indexOf(" ", start);
if(end != -1){
String to = msg.substring(start, end);
String msg2 = msg.substring(end+1);
Object obj = hm.get(to);
if(obj != null){
PrintWriter pw = (PrintWriter)obj;
pw.println(id + " whisphered. : " + msg2);
pw.flush();
} // if
}
} // sendmsg
public void broadcast(String msg){
synchronized(hm){
Collection collection = hm.values();
Iterator iter = collection.iterator();
while(iter.hasNext()){
PrintWriter pw = (PrintWriter)iter.next();
pw.println(msg);
pw.flush();
}
}
} // broadcast
}