자바로 작성하는 기초 채팅 프로그램(서버)


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
import java.net.*;
import java.util.*;

class ChatServer {
ServerSocket ss;
Vector<ChatHandler> v = new Vector<ChatHandler>();

public ChatServer() {
try {
ss = new ServerSocket(9500);
System.out.println("서버준비완료...");
while (true) {
Socket so = ss.accept();// 클라이어트를 낚아챈다
ChatHandler ch = new ChatHandler(this, so);
ch.start();
}
} catch (java.io.IOException io) {
io.printStackTrace();
}
}

public void register(ChatHandler ch) {
v.add(ch);
}

public void unregister(ChatHandler ch) {
v.remove(ch);
}

public void broadcast(String msg) {
Iterator<ChatHandler> it = v.iterator();
while (it.hasNext()) {
// ChatHandler ch = (ChatHandler)it.next();
ChatHandler ch = it.next();
ch.getPrintWriter().println(msg);
ch.getPrintWriter().flush();
}
}

public static void main(String[] args) {
new ChatServer();
}
}