-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer2.java
More file actions
88 lines (77 loc) · 2.94 KB
/
ChatServer2.java
File metadata and controls
88 lines (77 loc) · 2.94 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
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer2 {
private static final int PORT = 5000;
private static Set<ClientHandler> clientHandlers = new HashSet<>();
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Chat server started...");
while (true) {
Socket clientSocket = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(clientSocket);
clientHandlers.add(clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Broadcast message to all clients
private static synchronized void broadcast(String message, ClientHandler sender) {
for (ClientHandler client : clientHandlers) {
if (client != sender) {
client.sendMessage(message);
}
}
}
// Remove a client from the active list
private static synchronized void removeClient(ClientHandler clientHandler) {
clientHandlers.remove(clientHandler);
}
static class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private boolean active = true;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("New client connected: " + socket);
String message;
while (active && (message = in.readLine()) != null) {
System.out.println("Received: " + message);
if (message.equalsIgnoreCase("bye")) {
active = false;
out.println("bye"); // Send goodbye to client
break;
}
broadcast(message, this);
}
} catch (IOException e) {
System.out.println("Client disconnected.");
} finally {
closeResources();
}
}
public void sendMessage(String message) {
out.println(message);
}
private void closeResources() {
try {
if (out != null) out.close();
if (in != null) in.close();
if (socket != null) socket.close();
removeClient(this);
System.out.println("Client connection closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}