자바로 작성하는 기초 채팅 프로그램(핸들러)


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

class ChatHandler extends Thread {

private ChatServer cs;
private Socket so;
private BufferedReader br;
private PrintWriter pw;

public ChatHandler(ChatServer cs, Socket so) throws IOException {
this.cs = cs;
this.so = so;
br = new BufferedReader(new InputStreamReader(so.getInputStream()));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
so.getOutputStream())));
}

public void run() {
String name = null;
try {
name = br.readLine();
cs.register(this); // 벡터에 등록
cs.broadcast(name + "님이 입장하셨습니다...");

while (true) {
String data = br.readLine();
if (data == null || data.toLowerCase().equals("quit"))
break;

cs.broadcast("[" + name + "]" + data);
}
} catch (IOException io) {
io.printStackTrace();
}

// -------------

cs.unregister(this); // 벡테에서 제거
cs.broadcast(name + "님이 퇴장하셨습니다..");
try {
br.close();
pw.close();
so.close();
} catch (IOException io) {
io.printStackTrace();
}
}

public PrintWriter getPrintWriter() {
return pw;
}
}