-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChatClient.java
More file actions
77 lines (72 loc) · 3.32 KB
/
ChatClient.java
File metadata and controls
77 lines (72 loc) · 3.32 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/** Simple console client so you can run: java ChatClient [host] [port] */
public class ChatClient {
public static void main(String[] args) {
String host = args.length > 0 ? args[0] : "127.0.0.1";
int port = 5000;
if (args.length > 1) {
try { port = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) {}
}
System.out.println("[Client] Connecting to " + host + ":" + port);
try (Socket socket = new Socket(host, port);
BufferedReader serverIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter serverOut = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in))) {
// Thread to read messages from server
Thread reader = new Thread(() -> {
String line;
try {
while ((line = serverIn.readLine()) != null) {
System.out.println(line);
}
System.out.println("[Client] Server closed connection.");
} catch (IOException e) {
System.out.println("[Client] Reader stopped: " + e.getMessage());
}
});
reader.setDaemon(true);
reader.start();
// Main loop: read from stdin and send
String input;
while ((input = stdin.readLine()) != null) {
String trimmed = input.trim();
if (trimmed.startsWith("/sendfile")) {
// /sendfile <path> OR /sendfile <user> <path>
String[] parts = trimmed.split("\\s+");
if (parts.length == 2) {
String path = parts[1];
sendFile(host, port + 1, "*", path);
} else if (parts.length >= 3) {
String user = parts[1];
String path = parts[2];
sendFile(host, port + 1, user, path);
} else {
System.out.println("[Client] Usage: /sendfile (<user>) <path>");
}
continue; // do not send command to server as chat text
}
serverOut.println(input);
if ("/quit".equalsIgnoreCase(trimmed)) {
break; // allow finally to close socket
}
}
System.out.println("[Client] Disconnecting...");
} catch (IOException e) {
System.err.println("[Client] Error: " + e.getMessage());
}
}
private static void sendFile(String host, int filePort, String target, String path) {
System.out.println("[Client] Sending file '" + path + "' to " + ("*".equals(target) ? "ALL" : target) + " via port " + filePort);
FileSender sender = new FileSender(host, filePort);
try {
sender.sendFile(target, path);
System.out.println("[Client] File sent: " + path);
} catch (IOException e) {
System.err.println("[Client] File send failed: " + e.getMessage());
}
}
}