Complete network chat system with file sharing #1

Merged
peyman merged 1 commits from develop into main 2026-07-23 20:29:19 +00:00
4 changed files with 266 additions and 57 deletions
@@ -1,18 +1,54 @@
package com.university.chat.Client; 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{ public class ServerListener implements Runnable{
// TODO: store the ObjectInputStream from the user socket private final ObjectInputStream in;
// (this should be the same input stream the
// chatClient created when connecting) public ServerListener(ObjectInputStream in) {
this.in = in;
}
@Override @Override
public void run() { public void run() {
try { try {
// TODO: In an infinite loop read objects from the server while (true) {
// - if it's a ChatMessage -> print "<sender>: <content>" Object obj = in.readObject();
// - if it's a FileMessage -> print that a file was received if (obj instanceof ChatMessage) {
// (filename + sender), it's already ChatMessage msg = (ChatMessage) obj;
// saved to disk by the server. switch (msg.getType()) {
case LOGIN_SUCCESS:
System.out.println("\n[Server] " + msg.getContent());
break;
case LOGIN_FAILED:
System.out.println("\n[Server] " + msg.getContent());
System.exit(0);
break;
case PUBLIC_MESSAGE:
System.out.println("\n[" + msg.getSender() + "]: " + msg.getContent());
break;
case PRIVATE_MESSAGE:
System.out.println("\n[Private from " + msg.getSender() + "]: " + msg.getContent());
break;
case USER_LIST:
System.out.println("\n[Online users]: " + msg.getContent());
break;
default:
System.out.println("\n[Server] " + msg.getContent());
}
System.out.print("> ");
} else if (obj instanceof FileMessage) {
FileMessage fileMsg = (FileMessage) obj;
System.out.println("\n[File received] from " + fileMsg.getSender() +
": " + fileMsg.getFilename() + " (saved to server_data)");
System.out.print("> ");
}
}
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
@@ -1,29 +1,112 @@
package com.university.chat.Client; package com.university.chat.Client;
public class chatClient { import com.university.chat.Common.ChatMessage;
public static void main() { import com.university.chat.Common.FileMessage;
// TODO: Connecting to the server import com.university.chat.Common.MessageType;
// 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){ import java.io.*;
try { import java.net.Socket;
// TODO: Program loop — read a line from the console and act on it: import java.nio.file.Files;
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE import java.nio.file.Path;
// - "/users" -> build & send a USER_LIST request import java.nio.file.Paths;
// - "/sendfile <user> <path>" -> read the file into a byte[] import java.util.Scanner;
// (you can use TransferProgress
// to show progress) public class chatClient {
// and send it as a FileMessage
// - anything else -> send a PUBLIC_MESSAGE private static ObjectOutputStream out;
// Remember to flush() the output stream after writeObject(). private static ObjectInputStream in;
} catch (Exception e){ 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()); System.out.println("command failed: " + e.getMessage());
} }
} }
socket.close();
scanner.close();
} catch (Exception e) {
System.out.println("Connection error: " + e.getMessage());
}
} }
} }
@@ -1,15 +1,26 @@
package com.university.chat.Server; package com.university.chat.Server;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer { public class ChatServer {
// TODO: declare a single shared UserManager instance (static final) private static final UserManager userManager = new UserManager();
// This MUST be shared by all ClientSession threads so that
// broadcasting and private messaging work correctly.
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket final int PORT = 12345;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Chat Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getInetAddress());
ClientSession session = new ClientSession(clientSocket, userManager);
new Thread(session).start();
}
} catch (Exception e) {
System.err.println("Server error: " + e.getMessage());
}
// TODO: In an infinite loop:
// accept an incoming client connection
// make a new thread running ClientSession for each user.
} }
} }
@@ -2,44 +2,94 @@ package com.university.chat.Server;
import com.university.chat.Common.ChatMessage; import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage; import com.university.chat.Common.FileMessage;
import com.university.chat.Common.MessageType;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket; import java.net.Socket;
import java.nio.file.Files; import java.nio.file.Files;
public class ClientSession implements Runnable { public class ClientSession implements Runnable {
private final Socket socket;
private final UserManager userManager;
private ObjectOutputStream out;
private ObjectInputStream in;
private String username; private String username;
public ClientSession(Socket socket, UserManager userManager) { public ClientSession(Socket socket, UserManager userManager) {
// TODO : Create an ObjectOutputStream from socket.getOutputStream() this.socket = socket;
// and an ObjectInputStream from socket.getInputStream(). this.userManager = userManager;
try {
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
System.err.println("Error initializing streams: " + e.getMessage());
try {
socket.close();
} catch (IOException ignored) {}
}
} }
@Override @Override
public void run() { public void run() {
try { try {
if (out == null || in == null) {
return;
}
// TODO: Welcome the user (login step) Object first = in.readObject();
// 1. Read the first object sent by the client. if (!(first instanceof ChatMessage)) {
// 2. Check it's a ChatMessage with type LOGIN. socket.close();
// 3. Extract the username. return;
// 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 ChatMessage loginMsg = (ChatMessage) first;
// In a loop, call in.readObject(), you can separate messages by their type: if (loginMsg.getType() != MessageType.LOGIN) {
// - if it's a ChatMessage -> call handleChatMessage(msg) socket.close();
// - if it's a FileMessage -> call handleFileMessage(fileMsg) return;
// Keep looping until the connection is closed (an exception will be thrown). }
String requestedUsername = loginMsg.getSender();
if (!userManager.addUser(requestedUsername, this)) {
ChatMessage failure = new ChatMessage(MessageType.LOGIN_FAILED, "Server", null,
"Username '" + requestedUsername + "' is already taken.");
out.writeObject(failure);
out.flush();
socket.close();
return;
}
this.username = requestedUsername;
FileManager.createUserFolders(username);
ChatMessage success = new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", null,
"Welcome " + username + "!");
out.writeObject(success);
out.flush();
System.out.println("User logged in: " + username);
while (true) {
Object obj = in.readObject();
if (obj instanceof ChatMessage) {
handleChatMessage((ChatMessage) obj);
} else if (obj instanceof FileMessage) {
handleFileMessage((FileMessage) obj);
}
}
} catch (Exception e) { } catch (Exception e) {
System.out.println("Disconnected: " + username); System.out.println("Disconnected: " + username);
} finally { } finally {
// TODO: Remove the user from UserManager so they no longer if (username != null) {
// receive broadcasts or appear in users list userManager.removeUser(username);
}
try {
socket.close();
} catch (IOException ignored) {}
} }
} }
@@ -47,14 +97,34 @@ public class ClientSession implements Runnable {
private void handleChatMessage(ChatMessage msg) throws IOException { private void handleChatMessage(ChatMessage msg) throws IOException {
switch (msg.getType()) { switch (msg.getType()) {
case PUBLIC_MESSAGE -> { case PUBLIC_MESSAGE -> {
// TODO: Broadcast this message to every connected client. for (ClientSession session : userManager.getAllSessions()) {
session.out.writeObject(msg);
session.out.flush();
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user. String receiver = msg.getReceiver();
ClientSession target = userManager.getUser(receiver);
if (target != null) {
target.out.writeObject(msg);
target.out.flush();
} else {
ChatMessage error = new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server",
msg.getSender(), "User '" + receiver + "' is not online.");
out.writeObject(error);
out.flush();
}
} }
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users. String list = userManager.listUsers();
ChatMessage reply = new ChatMessage(MessageType.USER_LIST, "Server",
msg.getSender(), list);
out.writeObject(reply);
out.flush();
} }
default -> {
}
} }
} }
@@ -66,6 +136,15 @@ public class ClientSession implements Runnable {
Files.write(sentPath, fileMsg.getData()); Files.write(sentPath, fileMsg.getData());
Files.write(recvPath, fileMsg.getData()); Files.write(recvPath, fileMsg.getData());
// TODO: Forward the received file-message to the destination user. ClientSession target = userManager.getUser(fileMsg.getReceiver());
if (target != null) {
target.out.writeObject(fileMsg);
target.out.flush();
}else {
ChatMessage error = new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server",
fileMsg.getSender(), "User '" + fileMsg.getReceiver() + "' is not online. File saved on server.");
out.writeObject(error);
out.flush();
}
} }
} }