Add base files
This commit is contained in:
+43
@@ -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
|
||||
Generated
+10
@@ -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/
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding">
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+14
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/pom.xml" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -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<String, ClientSession>`). Already complete.
|
||||
* **FileManager** – manages per-user folders on disk (`server_data/<username>/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 <username> <message> → private message
|
||||
/users → list online users
|
||||
/sendfile <username> <filepath> → send a file
|
||||
<anything else> → 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
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>21</version>
|
||||
</dependency>
|
||||
```
|
||||
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.
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>socket</groupId>
|
||||
<artifactId>SocketProgramming</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>25</maven.compiler.source>
|
||||
<maven.compiler.target>25</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -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 "<sender>: <content>"
|
||||
// - 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <user> <text>" -> build & send a PRIVATE_MESSAGE
|
||||
// - "/users" -> build & send a USER_LIST request
|
||||
// - "/sendfile <user> <path>" -> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class UserManager {
|
||||
|
||||
private final ConcurrentHashMap<String, ClientSession> 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<ClientSession> getAllSessions() {
|
||||
return users.values();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user