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.net.UnknownHostException; import java.util.Scanner; public class chatClient { private static Socket socket; private static ObjectOutputStream out; private static ObjectInputStream in; private static String username; public static void main() { Scanner scanner = new Scanner(System.in); try { socket = new Socket("localhost", 5000); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); System.out.print("Enter your username: "); username = scanner.nextLine(); ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, null, ""); out.writeObject(loginMsg); out.flush(); ServerListener listener = new ServerListener(in); Thread thread = new Thread(listener); thread.start(); System.out.println("Connected!"); while (true) { try { String input = scanner.nextLine(); if (input.startsWith("/msg ")) { String[] parts = input.split(" ", 3); if (parts.length >= 3) { String receiver = parts[1]; String content = parts[2]; ChatMessage msg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, receiver, content); out.writeObject(msg); out.flush(); } else { System.out.println("Usage: /msg "); } } else if (input.trim().equals("/users")) { ChatMessage req = new ChatMessage(MessageType.USER_LIST, username, null, ""); out.writeObject(req); out.flush(); } else if (input.startsWith("/sendfile ")) { String[] parts = input.split(" ", 3); if (parts.length >= 3) { String receiver = parts[1]; String filePath = parts[2]; sendFile(receiver, filePath); } else { System.out.println("Usage: /sendfile "); } } else { if (!input.isEmpty()) { ChatMessage msg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, input); out.writeObject(msg); out.flush(); } } } catch (Exception e) { System.out.println("command failed: " + e.getMessage()); } } } catch (UnknownHostException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } private static void sendFile(String receiver, String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { System.out.println("file not found : " + filePath); return; } long fileSize = file.length(); byte[] data = new byte[(int) fileSize]; try (FileInputStream fis = new FileInputStream(file)) { fis.read(data); } TransferProgress progress = new TransferProgress(fileSize); progress.update(fileSize); FileMessage fileMsg = new FileMessage(username, receiver, file.getName(), data); out.writeObject(fileMsg); out.flush(); System.out.println("Send file : " + file.getName()); } }