-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
105 lines (84 loc) · 2.9 KB
/
ChatServer.java
File metadata and controls
105 lines (84 loc) · 2.9 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
96
97
98
99
100
101
102
103
104
105
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatServer {
private static final int PORT = 8888;
private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Serwer czatu uruchomiony na porcie " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Nowy klient dołączył: " + clientSocket);
ClientHandler clientHandler = new ClientHandler(clientSocket);
executorService.execute(clientHandler);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private final Socket clientSocket;
private final PrintWriter out;
private final Scanner in;
public ClientHandler(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
this.out = new PrintWriter(clientSocket.getOutputStream(), true);
this.in = new Scanner(clientSocket.getInputStream());
}
@Override
public void run() {
try {
welcomeMessage();
String clientName = getClientName();
broadcast(clientName + " dołączył do czatu.");
while (true) {
String message = in.nextLine();
if ("exit".equalsIgnoreCase(message)) {
break;
}
broadcast(clientName + ": " + message);
}
broadcast(clientName + " opuścił czat.");
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void welcomeMessage() {
out.println("Witaj! Podaj swoje imię:");
}
private String getClientName() {
return in.nextLine();
}
private void broadcast(String message) {
synchronized (ChatServer.class) {
for (ClientHandler client : ClientHandlers.getClients()) {
client.out.println(message);
}
}
}
}
class ClientHandlers {
private static final java.util.List<ClientHandler> clients = new java.util.concurrent.CopyOnWriteArrayList<>();
private ClientHandlers() {
}
public static void addClient(ClientHandler clientHandler) {
clients.add(clientHandler);
}
public static void removeClient(ClientHandler clientHandler) {
clients.remove(clientHandler);
}
public static java.util.List<ClientHandler> getClients() {
return clients;
}
}