diff --git a/src/main/java/com/university/chat/Client/ServerListener.java b/src/main/java/com/university/chat/Client/ServerListener.java index b609d74..fe027f3 100644 --- a/src/main/java/com/university/chat/Client/ServerListener.java +++ b/src/main/java/com/university/chat/Client/ServerListener.java @@ -1,20 +1,40 @@ 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.ObjectInputStream; + public class ServerListener implements Runnable{ - // TODO: store the ObjectInputStream from the user socket - // (this should be the same input stream the - // chatClient created when connecting) + private final ObjectInputStream in; + + public ServerListener(ObjectInputStream in) { + this.in = in; + } @Override public void run() { try { - // TODO: In an infinite loop read objects from the server - // - if it's a ChatMessage -> print ": " - // - if it's a FileMessage -> print that a file was received - // (filename + sender), it's already - // saved to disk by the server. - } catch (Exception e){ - System.out.println("Disconnected from server"); + while (true) { + Object obj = in.readObject(); + + if (obj instanceof ChatMessage msg) { + if (msg.getType() == MessageType.USER_LIST) { + System.out.println("\n[Online Users]: " + msg.getContent()); + } else if (msg.getType() == MessageType.PRIVATE_MESSAGE) { + System.out.println("\n[Private] " + msg.getSender() + ": " + msg.getContent()); + } else { + System.out.println("\n" + msg.getSender() + ": " + msg.getContent()); + } + } else if (obj instanceof FileMessage fileMsg) { + System.out.println("\n[File Received] Filename: '" + fileMsg.getFilename() + + "' sent by " + fileMsg.getSender() + ". It is saved on the server disk."); + } + System.out.print("> "); // Keep a prompt symbol for console usability + } + } catch (Exception e) { + System.out.println("\nDisconnected from server."); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/university/chat/Client/chatClient.java b/src/main/java/com/university/chat/Client/chatClient.java index dae0bad..c8c7fe6 100644 --- a/src/main/java/com/university/chat/Client/chatClient.java +++ b/src/main/java/com/university/chat/Client/chatClient.java @@ -1,29 +1,155 @@ package com.university.chat.Client; -public class chatClient { - public static void main() { - // TODO: Connecting to the server - // 1. Create a socket and connect to the server - // 2. Create an ObjectOutputStream (out) and ObjectInputStream (in) - // from the socket's streams — output FIRST, then input. - // 2. Get the username, and send a LOGIN ChatMessage with that username - // 3. Start a new Thread running a ServerListener(in) so incoming - // messages are handled concurrently. +import com.university.chat.Common.ChatMessage; +import com.university.chat.Common.FileMessage; +import com.university.chat.Common.MessageType; - while (true){ +import java.io.File; +import java.io.FileInputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.Socket; +import java.util.Scanner; + +public class chatClient { + private static final String SERVER_HOST = "localhost"; + private static final int SERVER_PORT = 12345; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Socket socket = null; + ObjectOutputStream out = null; + ObjectInputStream in = null; + String username = ""; + + try { + System.out.print("Enter your username: "); + username = scanner.nextLine().trim(); + + if (username.isEmpty()) { + System.out.println("Username cannot be blank. Exiting..."); + return; + } + + // 1. Create socket connection + socket = new Socket(SERVER_HOST, SERVER_PORT); + + // 2. Setup Object streams — Output stream FIRST to avoid deadlocking handshake + out = new ObjectOutputStream(socket.getOutputStream()); + out.flush(); + in = new ObjectInputStream(socket.getInputStream()); + + // 3. Authenticate with LOGIN message + ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, "Server", ""); + out.writeObject(loginMsg); + out.flush(); + + // Wait for Server to validate + Object response = in.readObject(); + if (response instanceof ChatMessage reply) { + if (reply.getType() == MessageType.LOGIN_FAILED) { + System.out.println("Login Failed: " + reply.getContent()); + socket.close(); + return; + } else if (reply.getType() == MessageType.LOGIN_SUCCESS) { + System.out.println("System: Connected successfully! " + reply.getContent()); + } + } + + // 4. Start listening thread for concurrent receipt + Thread listenerThread = new Thread(new ServerListener(in)); + listenerThread.setDaemon(true); + listenerThread.start(); + + // 5. Main loop for typing interactive user input + System.out.println("Use standard messages to chat. Commands:\n/msg \n/users\n/sendfile \n"); + + while (true) { + String input = scanner.nextLine(); + if (input.equalsIgnoreCase("/exit")) { + System.out.println("Exiting chat..."); + break; + } + + if (input.trim().isEmpty()) { + continue; + } + + try { + if (input.startsWith("/msg ")) { + // Pattern: /msg + String[] parts = input.substring(5).split(" ", 2); + if (parts.length < 2) { + System.out.println("Usage: /msg "); + continue; + } + String recipient = parts[0]; + String text = parts[1]; + ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, recipient, text); + out.writeObject(privateMsg); + out.flush(); + + } else if (input.equalsIgnoreCase("/users")) { + ChatMessage listRequest = new ChatMessage(MessageType.USER_LIST, username, "Server", ""); + out.writeObject(listRequest); + out.flush(); + + } else if (input.startsWith("/sendfile ")) { + // Pattern: /sendfile + String[] parts = input.substring(10).split(" ", 2); + if (parts.length < 2) { + System.out.println("Usage: /sendfile "); + continue; + } + String recipient = parts[0]; + String filepath = parts[1]; + + File file = new File(filepath); + if (!file.exists() || !file.isFile()) { + System.out.println("Error: File " + filepath + " does not exist."); + continue; + } + + // Load and read the file with a visual progress bar + byte[] fileBytes = new byte[(int) file.length()]; + try (FileInputStream fis = new FileInputStream(file)) { + TransferProgress progress = new TransferProgress(file.length()); + int bytesRead; + int totalRead = 0; + byte[] buffer = new byte[4096]; + + while ((bytesRead = fis.read(buffer)) != -1) { + System.arraycopy(buffer, 0, fileBytes, totalRead, bytesRead); + totalRead += bytesRead; + progress.update(totalRead); + } + } + + FileMessage fileMsg = new FileMessage(username, recipient, file.getName(), fileBytes); + out.writeObject(fileMsg); + out.flush(); + System.out.println("File sent successfully!"); + + } else { + // Treat as plain text PUBLIC message + ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "All", input); + out.writeObject(publicMsg); + out.flush(); + } + } catch (Exception e) { + System.out.println("Command failed: " + e.getMessage()); + } + } + + } catch (Exception e) { + System.err.println("Fatal connection exception: " + e.getMessage()); + } finally { + scanner.close(); try { - // TODO: Program loop — read a line from the console and act on it: - // - "/msg " -> build & send a PRIVATE_MESSAGE - // - "/users" -> build & send a USER_LIST request - // - "/sendfile " -> read the file into a byte[] - // (you can use TransferProgress - // to show progress) - // and send it as a FileMessage - // - anything else -> send a PUBLIC_MESSAGE - // Remember to flush() the output stream after writeObject(). - } catch (Exception e){ - System.out.println("command failed: " + e.getMessage()); + if (socket != null && !socket.isClosed()) socket.close(); + } catch (Exception e) { + // Ignore silent close exceptions } } } -} +} \ No newline at end of file diff --git a/src/main/java/com/university/chat/Server/ChatServer.java b/src/main/java/com/university/chat/Server/ChatServer.java index b2a35ae..936651f 100644 --- a/src/main/java/com/university/chat/Server/ChatServer.java +++ b/src/main/java/com/university/chat/Server/ChatServer.java @@ -1,15 +1,34 @@ package com.university.chat.Server; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + public class ChatServer { - // TODO: declare a single shared UserManager instance (static final) - // This MUST be shared by all ClientSession threads so that - // broadcasting and private messaging work correctly. + private static final UserManager userManager = new UserManager(); + private static final int PORT = 12345; // Default port public static void main(String[] args) { - // TODO: Create a ServerSocket + System.out.println("Starting Chat Server on port " + PORT + "..."); + try (ServerSocket serverSocket = new ServerSocket(PORT)) { + System.out.println("Server started successfully. Waiting for clients..."); - // TODO: In an infinite loop: - // accept an incoming client connection - // make a new thread running ClientSession for each user. + while (true) { + try { + + Socket clientSocket = serverSocket.accept(); + System.out.println("New client connection from: " + clientSocket.getRemoteSocketAddress()); + + // Create a new ClientSession task and run it in its own thread + ClientSession session = new ClientSession(clientSocket, userManager); + Thread clientThread = new Thread(session); + clientThread.start(); + } catch (IOException e) { + System.err.println("Error accepting client connection: " + e.getMessage()); + } + } + } catch (IOException e) { + System.err.println("Could not listen on port " + PORT + ": " + e.getMessage()); + } } -} +} \ No newline at end of file diff --git a/src/main/java/com/university/chat/Server/ClientSession.java b/src/main/java/com/university/chat/Server/ClientSession.java index f09d64a..243ded5 100644 --- a/src/main/java/com/university/chat/Server/ClientSession.java +++ b/src/main/java/com/university/chat/Server/ClientSession.java @@ -2,70 +2,164 @@ package com.university.chat.Server; import com.university.chat.Common.ChatMessage; import com.university.chat.Common.FileMessage; +import com.university.chat.Common.MessageType; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.net.Socket; import java.nio.file.Files; public class ClientSession implements Runnable { + private final Socket socket; + private final UserManager userManager; + private ObjectOutputStream out; + private ObjectInputStream in; private String username; public ClientSession(Socket socket, UserManager userManager) { - // TODO : Create an ObjectOutputStream from socket.getOutputStream() - // and an ObjectInputStream from socket.getInputStream(). + this.socket = socket; + this.userManager = userManager; + try { + // Output stream MUST be created first to prevent stream deadlock + this.out = new ObjectOutputStream(socket.getOutputStream()); + this.out.flush(); + this.in = new ObjectInputStream(socket.getInputStream()); + } catch (IOException e) { + System.err.println("Error initializing streams for client: " + e.getMessage()); + closeResources(); + } } @Override public void run() { + if (in == null || out == null) { + return; + } + try { + // 1. Welcome the user (login step) + Object firstObj = in.readObject(); + if (!(firstObj instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) { + sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", "", "Invalid connection sequence.")); + closeResources(); + return; + } - // TODO: Welcome the user (login step) - // 1. Read the first object sent by the client. - // 2. Check it's a ChatMessage with type LOGIN. - // 3. Extract the username. - // 4. Try to register the user via userManager.addUser(...). - // 5. If the username is taken, send back LOGIN_FAILED and close the socket. - // 6. Otherwise, create the user's folders with FileManager.createUserFolders(...) - // and send back LOGIN_SUCCESS. + this.username = loginMsg.getSender(); + if (this.username == null || this.username.trim().isEmpty()) { + sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", "", "Username cannot be empty.")); + closeResources(); + return; + } - // TODO: Main message loop - // In a loop, call in.readObject(), you can separate messages by their type: - // - if it's a ChatMessage -> call handleChatMessage(msg) - // - if it's a FileMessage -> call handleFileMessage(fileMsg) - // Keep looping until the connection is closed (an exception will be thrown). + // 2. Register user + if (!userManager.addUser(this.username, this)) { + sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", this.username, "Username already taken.")); + closeResources(); + return; + } + + // 3. Setup workspace & approve login + FileManager.createUserFolders(this.username); + sendDirect(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", this.username, "Welcome to the chat!")); + System.out.println("User online: " + this.username); + + // + broadcast(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "All", this.username + " has joined the chat.")); + + // 4. Main message loop + while (true) { + Object obj = in.readObject(); + if (obj instanceof ChatMessage msg) { + handleChatMessage(msg); + } else if (obj instanceof FileMessage fileMsg) { + handleFileMessage(fileMsg); + } + } } catch (Exception e) { - System.out.println("Disconnected: " + username); + System.out.println("Disconnected: " + (username != null ? username : "Unknown client")); } finally { - // TODO: Remove the user from UserManager so they no longer - // receive broadcasts or appear in users list + cleanup(); } } - private void handleChatMessage(ChatMessage msg) throws IOException { switch (msg.getType()) { - case PUBLIC_MESSAGE -> { - // TODO: Broadcast this message to every connected client. - } + case PUBLIC_MESSAGE -> broadcast(msg); case PRIVATE_MESSAGE -> { - // TODO: Forward this message to the receiver user. + ClientSession recipient = userManager.getUser(msg.getReceiver()); + if (recipient != null) { + recipient.sendDirect(msg); + } else { + sendDirect(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", this.username, "User " + msg.getReceiver() + " is offline.")); + } } case USER_LIST -> { - // TODO: Reply to the requester with the list of online users. + String users = userManager.listUsers(); + sendDirect(new ChatMessage(MessageType.USER_LIST, "Server", this.username, users)); } + default -> {} } } private void handleFileMessage(FileMessage fileMsg) throws IOException { - // Storing the file + // Storing the file on the server side var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename()); var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), fileMsg.getFilename()); Files.write(sentPath, fileMsg.getData()); Files.write(recvPath, fileMsg.getData()); - // TODO: Forward the received file-message to the destination user. + // Forward the received file-message to the destination user. + ClientSession recipient = userManager.getUser(fileMsg.getReceiver()); + if (recipient != null) { + recipient.sendDirect(fileMsg); + } else { + sendDirect(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", this.username, "Could not deliver file. User " + fileMsg.getReceiver() + " is offline.")); + } + } + + // Helper to send directly to this session's socket + public synchronized void sendDirect(Object obj) { + try { + out.writeObject(obj); + out.flush(); + } catch (IOException e) { + System.err.println("Error sending message to " + username + ": " + e.getMessage()); + } + } + + // Broadcasts to all users except sender + private void broadcast(ChatMessage msg) { + for (ClientSession session : userManager.getAllSessions()) { + if (!session.getUsername().equals(this.username)) { + session.sendDirect(msg); + } + } + } + + public String getUsername() { + return username; + } + + private void cleanup() { + if (username != null) { + userManager.removeUser(username); + broadcast(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "All", username + " has left the chat.")); + } + closeResources(); + } + + private void closeResources() { + try { + if (in != null) in.close(); + if (out != null) out.close(); + if (socket != null && !socket.isClosed()) socket.close(); + } catch (IOException e) { + System.err.println("Error closing resources: " + e.getMessage()); + } } } \ No newline at end of file diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..6885a5c --- /dev/null +++ b/test.txt @@ -0,0 +1 @@ +salammmmmm.