-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServerThread.java
More file actions
81 lines (68 loc) · 1.65 KB
/
ServerThread.java
File metadata and controls
81 lines (68 loc) · 1.65 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
package java_ssp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ServerThread extends Thread{
private Socket socket;
private BufferedReader br = null;
private PrintWriter pw = null;
private String userIP =null;
static List<PrintWriter> list = Collections.synchronizedList(new ArrayList<PrintWriter>());
ServerThread(Socket s)
{
socket =s;
userIP= socket.getInetAddress().toString();
pw = new PrintWriter(socket.getOutputStream(), true);
list.add(pw);
}
public void run(){
try {
service();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("**"+userIP+"님 접속 종료.");
}finally {
try {
list.remove(pw);
sendAll()
closeAll();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void service()throws IOException{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = null;
while(true){
str = br.readLine();
if(str == null){
System.out.println(userIP+"님이 연결을 종료했습니다.");
break;
}
System.out.println(userIP+"님: "+str);
sendAll(str);
}
}
private void sendAll(String str) {
for(PrintWriter writer: list)
{
writer.println(str);
writer.flush();
}
}
public void closeAll()throws IOException{
if (pw != null)
pw.close();
if (br != null)
br.close();
if (socket != null)
socket.close();
}
}