Files
HW-10-Socket-Programming/src/main/java/com/university/chat/Client/chatClient.java
T

113 lines
4.4 KiB
Java

package com.university.chat.Client;
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
import com.university.chat.Common.MessageType;
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class chatClient {
private static ObjectOutputStream out;
private static ObjectInputStream in;
private static String username;
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your username: ");
username = scanner.nextLine().trim();
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, null, "");
out.writeObject(loginMsg);
out.flush();
ServerListener listener = new ServerListener(in);
new Thread(listener).start();
while (true){
try {
System.out.print("> ");
String line = scanner.nextLine();
if (line == null) break;
if (line.equals("/exit") || line.equals("/quit")) {
System.out.println("Disconnecting...");
break;
}
if (line.startsWith("/msg ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /msg <username> <message>");
continue;
}
String target = parts[1];
String content = parts[2];
ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE,
username, target, content);
out.writeObject(privateMsg);
out.flush();
} else if (line.equals("/users")) {
ChatMessage userListReq = new ChatMessage(MessageType.USER_LIST,
username, null, "");
out.writeObject(userListReq);
out.flush();
} else if (line.startsWith("/sendfile ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /sendfile <username> <filepath>");
continue;
}
String target = parts[1];
String filePath = parts[2];
Path path = Paths.get(filePath);
if (!Files.exists(path) || Files.isDirectory(path)) {
System.out.println("File does not exist or is a directory.");
continue;
}
byte[] data = Files.readAllBytes(path);
String filename = path.getFileName().toString();
TransferProgress progress = new TransferProgress(data.length);
progress.update(data.length);
FileMessage fileMsg = new FileMessage(username, target, filename, data);
out.writeObject(fileMsg);
out.flush();
System.out.println("File sent to " + target);
} else {
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE,
username, null, line);
out.writeObject(publicMsg);
out.flush();
}
}catch (IOException e) {
System.out.println("Connection lost. Exiting...");
break;
} catch (Exception e){
System.out.println("command failed: " + e.getMessage());
}
}
socket.close();
scanner.close();
} catch (Exception e) {
System.out.println("Connection error: " + e.getMessage());
}
}
}