-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
65 lines (59 loc) · 2.41 KB
/
Copy pathChatServer.java
File metadata and controls
65 lines (59 loc) · 2.41 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
import java.io.*;
import java.net.*;
import java.util.*;
// ChatServer: waits for clients (Student, Teacher) to connect and relays messages to all
public class ChatServer {
// Keep track of all connected clients' output streams
private static Set<PrintWriter> clientWriters = new HashSet<>();
public static void main(String[] args) throws IOException {
// Create a server socket listening on port 1234
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server started on port 1234");
// Accept clients forever
while (true) {
Socket socket = serverSocket.accept(); // wait for a client
System.out.println("Client connected");
// Handle each client in a separate thread
new Thread(new ClientHandler(socket)).start();
}
}
// Inner class: handles communication with one client
private static class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
// Input stream: read messages from client
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Output stream: send messages to client
this.out = new PrintWriter(socket.getOutputStream(), true);
// Add this client's output stream to the set
synchronized (clientWriters) {
clientWriters.add(out);
}
}
public void run() {
try {
String message;
// Continuously read messages from this client
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
// Broadcast message to all connected clients
synchronized (clientWriters) {
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Remove client when disconnected
synchronized (clientWriters) {
clientWriters.remove(out);
}
}
}
}
}