Repository navigation
Expand file tree
/
Copy pathChatServer.java
More file actions
72 lines (58 loc) · 2.21 KB
/
Copy pathChatServer.java
File metadata and controls
72 lines (58 loc) · 2.21 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
//챗 서버 : connected by client[127.0.0.1:52971]
//챗 서버 : 신동헌 참여했습니다!
//챗 서버 : 신동헌: 안녕하세요.
//챗 서버 : connected by client[127.0.0.1:52975]
//챗 서버 : 김동현 참여했습니다!
//챗 서버 : 김동현: 안녕하세요
//챗 서버 : 김동현: 반갑습니다
//챗 서버 : 신동헌: 안뇨 압바갑섭
//챗 서버 : connected by client[127.0.0.1:52981]
//챗 서버 : 이동헌 참여했습니다!
//챗 서버 : 이동헌: 안녕
//챗 서버 : 이동헌 채팅을 떠났습니다.
package chat;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ChatServer {
private static final int PORT = 9000;
public static volatile int connectedClients = 0;
public static List<String> clientNames = Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) {
List<PrintWriter> listPrintWriter = new ArrayList<PrintWriter>();
ServerSocket serverSocket = null;
try {
//1. 소켓 서버 생성
serverSocket = new ServerSocket();
// 2. 바인딩
String hostAddress = InetAddress.getLocalHost().getHostAddress();
serverSocket.bind(new InetSocketAddress("127.0.0.1", PORT));
log("연결 기다림" + hostAddress + ":" + PORT);
// 3.요청대기
while (true) {
//3. wating for connection
Socket socket = serverSocket.accept();
Thread thread = new ChatServerThread(socket, listPrintWriter);
thread.start();
}
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
log("Error : " + e);
} finally {
try {
if (serverSocket != null && serverSocket.isClosed() == false) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void log(String log) {
System.out.println("챗 서버 : " + log);
}
}