-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatServer.java
72 lines (61 loc) · 2.05 KB
/
ChatServer.java
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
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ChatServer {
private List<PrintWriter> clients = new ArrayList<>();
public static void main(String[] args) {
new ChatServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is running on port 12345");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
clients.add(writer);
new Thread(new ClientHandler(clientSocket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void broadcastMessage(String message, PrintWriter sender) {
for (PrintWriter client : clients) {
if (client != sender) {
client.println(message);
}
}
}
private class ClientHandler implements Runnable {
private Socket socket;
private Scanner in;
public ClientHandler(Socket socket) {
this.socket = socket;
try {
this.in = new Scanner(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (in.hasNextLine()) {
String message = in.nextLine();
broadcastMessage(message, null);
}
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}