-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
47 lines (39 loc) · 1.53 KB
/
ChatServer.java
File metadata and controls
47 lines (39 loc) · 1.53 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
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class ChatServer {
private static final int PORT = 12345;
private static ArrayList<Socket> clients = new ArrayList<>();
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
clients.add(clientSocket);
System.out.println("New client connected: " + clientSocket.getInetAddress());
handleClient(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) {
try {
Scanner input = new Scanner(clientSocket.getInputStream());
OutputStream output = clientSocket.getOutputStream();
output.write("Welcome! Type your message:\n".getBytes());
while (input.hasNextLine()) {
String message = input.nextLine();
System.out.println("Client: " + message);
output.write(("Server: " + message + "\n").getBytes()); // Echo message back
}
input.close();
clientSocket.close();
clients.remove(clientSocket);
System.out.println("Client disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}