From 240eac05045f3977f1c748a16caee5a0ea3c4f95 Mon Sep 17 00:00:00 2001 From: Hosein Date: Fri, 12 Jun 2026 12:18:48 +0330 Subject: [PATCH] Add base files --- .gitignore | 43 ++++++ .idea/.gitignore | 10 ++ .idea/encodings.xml | 7 + .idea/misc.xml | 14 ++ .idea/vcs.xml | 6 + README.md | 134 ++++++++++++++++++ pom.xml | 17 +++ .../chat/Client/ServerListener.java | 20 +++ .../chat/Client/TransferProgress.java | 37 +++++ .../university/chat/Client/chatClient.java | 29 ++++ .../university/chat/Common/ChatMessage.java | 25 ++++ .../university/chat/Common/FileMessage.java | 36 +++++ .../university/chat/Common/MessageType.java | 13 ++ .../university/chat/Server/ChatServer.java | 15 ++ .../university/chat/Server/ClientSession.java | 71 ++++++++++ .../university/chat/Server/FileManager.java | 25 ++++ .../university/chat/Server/UserManager.java | 28 ++++ 17 files changed, 530 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/encodings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/vcs.xml create mode 100644 README.md create mode 100644 pom.xml create mode 100644 src/main/java/com/university/chat/Client/ServerListener.java create mode 100644 src/main/java/com/university/chat/Client/TransferProgress.java create mode 100644 src/main/java/com/university/chat/Client/chatClient.java create mode 100644 src/main/java/com/university/chat/Common/ChatMessage.java create mode 100644 src/main/java/com/university/chat/Common/FileMessage.java create mode 100644 src/main/java/com/university/chat/Common/MessageType.java create mode 100644 src/main/java/com/university/chat/Server/ChatServer.java create mode 100644 src/main/java/com/university/chat/Server/ClientSession.java create mode 100644 src/main/java/com/university/chat/Server/FileManager.java create mode 100644 src/main/java/com/university/chat/Server/UserManager.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52e5fba --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ +.kotlin +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +server_data/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..ab1f416 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d2b5d0f --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..610afd1 --- /dev/null +++ b/README.md @@ -0,0 +1,134 @@ +## Network File-Sharing chat System (Java) + +### Overview +This project is a multi-client network chat system with file sharing, implemented using **Java sockets**, **MUltithreading** and **Object Serialization**. +Clients connect to a central server and can: + +* send public chat message +* send private messages +* request the list of online users +* transfer files to other users + +communication between client and server is implemented using Java Object Streams(`ObjectInputStream` / `ObjectOutputStream`) so that structured objects can be transferred directly over the network. + + +--- +### Architecture + +1. **ChatServer** opens a `ServerSocket` and waits for connections. +2. Each connecting client gets its own **ClientSession** thread. +3. A shared **UserManager** tracks who's online and routes messages. +4. Everything is exchanged as serialized objects (`ChatMessage` / `FileMessage`). + +``` +Client → Socket → Server → ClientSession (thread) → UserManager → Broadcast/Route → Clients +``` + +--- + +### Message Protocol +Two serializable classes carry everything over the wire: + +* **ChatMessage** – text-based: logins, public/private messages, user-list requests, server replies. +* **FileMessage** – file transfers, carrying the file as a `byte[]`. + +`MessageType` is an enum (`LOGIN`, `LOGIN_SUCCESS`, `LOGIN_FAILED`, `PUBLIC_MESSAGE`, `PRIVATE_MESSAGE`, `USER_LIST`, …) so both sides agree on what each message means. + +--- + +### Package Structure +``` +com.university.chat +├── common → shared message classes (ChatMessage, FileMessage, MessageType) +├── server → server-side logic +└── client → client application +``` + +#### `common` +Already complete — these define the protocol and don't need any changes. + +#### `server` +* **ChatServer** – entry point. Opens the server socket and creates a `ClientSession` per client. +* **ClientSession** – one thread per client. Handles login, reads incoming messages, and dispatches them (broadcast, private message, user list, file transfer). +* **UserManager** – thread-safe registry of online users (`ConcurrentHashMap`). Already complete. +* **FileManager** – manages per-user folders on disk (`server_data//sent` and `received`). Already complete. + +#### `client` +* **chatClient** – entry point. Connects to the server, logs in, starts a listener thread, and runs the input loop for user commands. +* **ServerListener** – background thread that continuously reads and displays messages/files coming from the server. +* **TransferProgress** – small helper that prints a progress bar during file uploads. Already complete. + +--- + +### Client Commands +``` +/msg → private message +/users → list online users +/sendfile → send a file + → public message +``` + +--- + +### File Transfer Flow +1. Client reads the file and converts it to `byte[]`. +2. It's wrapped in a `FileMessage` and sent to the server. +3. The server saves a copy (in `sent/` for the sender, `received/` for the receiver) and forwards it to the recipient. + +--- + +### Threading Model +* **Server**: one `ClientSession` thread per connected client. +* **Client**: main thread handles user input, a `ServerListener` thread handles incoming messages — so you can chat and receive **at the same time**. + +--- + +## Your Task + +Several core pieces are left as **TODOs** for you to implement. Follow the comments in each file alongside the structure mentioned above to complete them. + +| File | What to implement | +|------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `Server/ChatServer.java` | Pick a port, create a shared `UserManager`, open the server socket, accept clients in a loop, and create a `ClientSession` thread per client. | +| `Server/ClientSession.java` | Set up object streams in the constructor; handle login (success/failure); receive messages in a loop and dispatch `ChatMessage`/`FileMessage`; broadcast, private message, and user-list logic; remove user on disconnect; forward files. | +| `Client/chatClient.java` | Connect to the server, set up streams, log in, start `ServerListener`, and implement the command loop (`/msg`, `/users`, `/sendfile`, plain messages). | +| `Client/ServerListener.java` | Continuously read objects from the server and print chat messages / file-received notifications. | + +**Tips:** +* Always create the `ObjectOutputStream` *before* the `ObjectInputStream` on both ends — this avoids a stream-handshake deadlock. +* Don't forget `out.flush()` after `writeObject(...)`. +* Test with two or more client instances to verify broadcasting, private messages, and file transfer all work correctly. + +#### Running multiple clients in IntelliJ +1. Click the **⋮** icon next to the run button → **Edit Configurations** +2. Open **Modify options** (Alt+M) +3. Enable **Allow multiple instances** (Alt+U) + +--- + +## Optional Bonus: JavaFX UI + +If you want to go further replace the console client with a simple **JavaFX** GUI (chat window, online-user list, file-send button, etc.). + +1. **Add the JavaFX dependencies** to your `pom.xml` — for Maven: + ```xml + + org.openjfx + javafx-controls + 21 + + + org.openjfx + javafx-fxml + 21 + + ``` + You'll also need the `javafx-maven-plugin` to run the app from Maven. + + +2. **Create a JavaFX entry point**, e.g. `Client/ChatClientApp.java`, extending `javafx.application.Application` and implementing `start(Stage stage)`. This becomes your new launch class instead of (or alongside) `chatClient`. + + +3. Reuse your existing socket/streams logic — just move the "send" actions to button handlers and update the UI from `ServerListener` using `Platform.runLater(...)` (**since UI updates must happen on the JavaFX Application Thread**). + +This part is **completely optional** and won't affect your core grade — just a fun way to practice connecting a GUI to networking code and multithreading. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..c7c56af --- /dev/null +++ b/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + socket + SocketProgramming + 1.0-SNAPSHOT + + + 25 + 25 + UTF-8 + + + \ No newline at end of file diff --git a/src/main/java/com/university/chat/Client/ServerListener.java b/src/main/java/com/university/chat/Client/ServerListener.java new file mode 100644 index 0000000..b609d74 --- /dev/null +++ b/src/main/java/com/university/chat/Client/ServerListener.java @@ -0,0 +1,20 @@ +package com.university.chat.Client; + +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) + + @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"); + } + } +} diff --git a/src/main/java/com/university/chat/Client/TransferProgress.java b/src/main/java/com/university/chat/Client/TransferProgress.java new file mode 100644 index 0000000..0e617a4 --- /dev/null +++ b/src/main/java/com/university/chat/Client/TransferProgress.java @@ -0,0 +1,37 @@ +package com.university.chat.Client; + +public class TransferProgress { + + private final long total; + private final long startTime; + private static final int WIDTH = 30; + + public TransferProgress(long total) { + this.total = total; + this.startTime = System.currentTimeMillis(); + } + + public void update(long current) { + + double percent = (double) current / total; + int filled = (int) (percent * WIDTH); + + StringBuilder bar = new StringBuilder("["); + for (int i = 0; i < WIDTH; i++) { + bar.append(i < filled ? "█" : " "); + } + bar.append("]"); + + long elapsed = System.currentTimeMillis() - startTime; + double speed = current / 1024.0 / 1024.0 / (elapsed / 1000.0 + 0.001); + + System.out.printf("\r%s %3d%% | %.2f MB/s", + bar, + (int) (percent * 100), + speed); + + if (current >= total) { + System.out.println(); + } + } +} diff --git a/src/main/java/com/university/chat/Client/chatClient.java b/src/main/java/com/university/chat/Client/chatClient.java new file mode 100644 index 0000000..dae0bad --- /dev/null +++ b/src/main/java/com/university/chat/Client/chatClient.java @@ -0,0 +1,29 @@ +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. + + while (true){ + 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()); + } + } + } +} diff --git a/src/main/java/com/university/chat/Common/ChatMessage.java b/src/main/java/com/university/chat/Common/ChatMessage.java new file mode 100644 index 0000000..c097745 --- /dev/null +++ b/src/main/java/com/university/chat/Common/ChatMessage.java @@ -0,0 +1,25 @@ +package com.university.chat.Common; + +import java.io.Serializable; + +public class ChatMessage implements Serializable { + + private static final long serialVersionUID = 1L; + + private MessageType type; + private String sender; + private String receiver; + private String content; + + public ChatMessage(MessageType type, String sender, String receiver, String content) { + this.type = type; + this.sender = sender; + this.receiver = receiver; + this.content = content; + } + + public MessageType getType() { return type; } + public String getSender() { return sender; } + public String getReceiver() { return receiver; } + public String getContent() { return content; } +} diff --git a/src/main/java/com/university/chat/Common/FileMessage.java b/src/main/java/com/university/chat/Common/FileMessage.java new file mode 100644 index 0000000..4f90fbf --- /dev/null +++ b/src/main/java/com/university/chat/Common/FileMessage.java @@ -0,0 +1,36 @@ +package com.university.chat.Common; + +import java.io.Serializable; + +public class FileMessage implements Serializable { + + private static final long SerialVersionUID = 1L; + + private String sender; + private String receiver; + private String filename; + private byte[] data; + + public FileMessage(String sender, String receiver, String filename, byte[] data) { + this.sender = sender; + this.receiver = receiver; + this.filename = filename; + this.data = data; + } + + public String getSender() { + return sender; + } + + public String getReceiver() { + return receiver; + } + + public String getFilename() { + return filename; + } + + public byte[] getData() { + return data; + } +} diff --git a/src/main/java/com/university/chat/Common/MessageType.java b/src/main/java/com/university/chat/Common/MessageType.java new file mode 100644 index 0000000..093ff8d --- /dev/null +++ b/src/main/java/com/university/chat/Common/MessageType.java @@ -0,0 +1,13 @@ +package com.university.chat.Common; + +import java.io.Serializable; + +public enum MessageType implements Serializable { + LOGIN, + LOGIN_SUCCESS, + LOGIN_FAILED, + PUBLIC_MESSAGE, + PRIVATE_MESSAGE, + USER_LIST, + FILE_TRANSFER +} diff --git a/src/main/java/com/university/chat/Server/ChatServer.java b/src/main/java/com/university/chat/Server/ChatServer.java new file mode 100644 index 0000000..b2a35ae --- /dev/null +++ b/src/main/java/com/university/chat/Server/ChatServer.java @@ -0,0 +1,15 @@ +package com.university.chat.Server; + +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. + + public static void main(String[] args) { + // TODO: Create a ServerSocket + + // TODO: In an infinite loop: + // accept an incoming client connection + // make a new thread running ClientSession for each user. + } +} diff --git a/src/main/java/com/university/chat/Server/ClientSession.java b/src/main/java/com/university/chat/Server/ClientSession.java new file mode 100644 index 0000000..f09d64a --- /dev/null +++ b/src/main/java/com/university/chat/Server/ClientSession.java @@ -0,0 +1,71 @@ +package com.university.chat.Server; + +import com.university.chat.Common.ChatMessage; +import com.university.chat.Common.FileMessage; + +import java.io.IOException; +import java.net.Socket; +import java.nio.file.Files; + +public class ClientSession implements Runnable { + + private String username; + + public ClientSession(Socket socket, UserManager userManager) { + // TODO : Create an ObjectOutputStream from socket.getOutputStream() + // and an ObjectInputStream from socket.getInputStream(). + } + + @Override + public void run() { + try { + + // 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. + + // 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). + + } catch (Exception e) { + System.out.println("Disconnected: " + username); + } finally { + // TODO: Remove the user from UserManager so they no longer + // receive broadcasts or appear in users list + } + } + + + private void handleChatMessage(ChatMessage msg) throws IOException { + switch (msg.getType()) { + case PUBLIC_MESSAGE -> { + // TODO: Broadcast this message to every connected client. + } + case PRIVATE_MESSAGE -> { + // TODO: Forward this message to the receiver user. + } + case USER_LIST -> { + // TODO: Reply to the requester with the list of online users. + } + } + } + + private void handleFileMessage(FileMessage fileMsg) throws IOException { + // Storing the file + 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. + } +} \ No newline at end of file diff --git a/src/main/java/com/university/chat/Server/FileManager.java b/src/main/java/com/university/chat/Server/FileManager.java new file mode 100644 index 0000000..0c2c715 --- /dev/null +++ b/src/main/java/com/university/chat/Server/FileManager.java @@ -0,0 +1,25 @@ +package com.university.chat.Server; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class FileManager { + + private static final String BASE_DIR = "server_data"; + + public static void createUserFolders(String username) throws IOException { + Path userPath = Paths.get(BASE_DIR, username); + Files.createDirectories(userPath.resolve("received")); + Files.createDirectories(userPath.resolve("sent")); + } + + public static Path getReceivedPath(String username, String filename) { + return Paths.get(BASE_DIR, username, "received", filename); + } + + public static Path getSentPath(String username, String filename) { + return Paths.get(BASE_DIR, username, "sent", filename); + } +} diff --git a/src/main/java/com/university/chat/Server/UserManager.java b/src/main/java/com/university/chat/Server/UserManager.java new file mode 100644 index 0000000..07cbc2d --- /dev/null +++ b/src/main/java/com/university/chat/Server/UserManager.java @@ -0,0 +1,28 @@ +package com.university.chat.Server; + +import java.util.concurrent.ConcurrentHashMap; + +public class UserManager { + + private final ConcurrentHashMap users = new ConcurrentHashMap<>(); + + public boolean addUser(String username, ClientSession session) { + return users.putIfAbsent(username, session) == null; + } + + public void removeUser(String username) { + users.remove(username); + } + + public ClientSession getUser(String username) { + return users.get(username); + } + + public String listUsers() { + return users.keySet().toString(); + } + + public Iterable getAllSessions() { + return users.values(); + } +}