Develop #1

Open
HadiSharifi wants to merge 7 commits from develop into main
5 changed files with 218 additions and 62 deletions
+2 -2
View File
@@ -9,8 +9,8 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>25</maven.compiler.source> <maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target> <maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
@@ -1,18 +1,37 @@
package com.university.chat.Client; package com.university.chat.Client;
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
import java.io.ObjectInputStream;
import java.net.Socket;
public class ServerListener implements Runnable{ public class ServerListener implements Runnable{
// TODO: store the ObjectInputStream from the user socket
// (this should be the same input stream the private final ObjectInputStream in;
// 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
// - if it's a ChatMessage -> print "<sender>: <content>" while (true) {
// - if it's a FileMessage -> print that a file was received Object obj = in.readObject();
// (filename + sender), it's already if (obj instanceof ChatMessage msg) {
// saved to disk by the server. System.out.println(msg.getSender() + ": " + msg.getContent());
}
else if (obj instanceof FileMessage file) {
System.out.println("[File received] '" + file.getFilename()
+ "' from " + file.getSender());
}
else if (obj instanceof String str) {
System.out.println(str);
}
}
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
@@ -1,29 +1,97 @@
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;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class chatClient { public class chatClient {
public static void main() { public static void main(String[] args) {
// TODO: Connecting to the server
// 1. Create a socket and connect to the server String host = "localhost";
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in) int port = 9000;
// 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 { try {
// TODO: Program loop — read a line from the console and act on it:
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE Socket socket = new Socket(host, port);
// - "/users" -> build & send a USER_LIST request ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
// - "/sendfile <user> <path>" -> read the file into a byte[] ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
// (you can use TransferProgress
// to show progress) Scanner sc = new Scanner(System.in);
// and send it as a FileMessage System.out.println("Enter your username: ");
// - anything else -> send a PUBLIC_MESSAGE String username = sc.nextLine();
// Remember to flush() the output stream after writeObject().
} catch (Exception e){ out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
out.flush();
Object loginResponse = in.readObject();
if (loginResponse instanceof ChatMessage response) {
if (response.getType() == MessageType.LOGIN_FAILED) {
System.out.println("Login failed: " + response.getContent());
socket.close();
return;
}
System.out.println(response.getContent());
}
Thread listenerThread = new Thread(new ServerListener(in));
listenerThread.setDaemon(true);
listenerThread.start();
while (true) {
try {
String line = sc.nextLine();
if (line.startsWith("/msg ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /msg <user> <text>");
continue;
}
String target = parts[1];
String text = parts[2];
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, target, text));
out.flush();
} else if (line.equals("/users")) {
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, null, null));
out.flush();
} else if (line.startsWith("/sendfile ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /sendfile <user> <filepath>");
continue;
}
String target = parts[1];
String filePath = parts[2];
byte[] fileData = Files.readAllBytes(Paths.get(filePath));
String filename = Paths.get(filePath).getFileName().toString();
TransferProgress progress = new TransferProgress(fileData.length);
progress.update(fileData.length);
out.writeObject(new FileMessage(username, target, filename, fileData));
out.flush();
System.out.println("File '" + filename + "' sent to " + target + ".");
} else {
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line));
out.flush();
}
} catch (Exception e) {
System.out.println("command failed: " + e.getMessage()); System.out.println("command failed: " + e.getMessage());
} }
} }
} catch (Exception e) {
System.out.println(" could not connect to " + host + ":" + port);
}
} }
} }
@@ -1,15 +1,26 @@
package com.university.chat.Server; package com.university.chat.Server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer { 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) { private static final UserManager userManager = new UserManager();
// TODO: Create a ServerSocket private static final int port = 9000;
// TODO: In an infinite loop: public static void main(String[] args) throws IOException {
// accept an incoming client connection
// make a new thread running ClientSession for each user. try( ServerSocket serverSocket = new ServerSocket(port)){
System.out.println("Server started on port " + port);
while(true){
Socket clientSocket = serverSocket.accept();
Thread clientThread = new Thread(new ClientSession(clientSocket,userManager));
clientThread.start();
}
}
catch (IOException e){
System.out.println("server error: " + e.getMessage());
}
} }
} }
@@ -2,70 +2,128 @@ 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 String username; private String username;
private Socket socket;
private UserManager userManager;
private ObjectOutputStream out;
private ObjectInputStream in;
public ClientSession(Socket socket, UserManager userManager) { 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 {
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
}
catch (IOException e) {
System.out.println("Failed to create streams: " + e.getMessage());
}
} }
@Override @Override
public void run() { public void run() {
try { try {
// TODO: Welcome the user (login step) Object firstObject = in.readObject();
// 1. Read the first object sent by the client. if (!(firstObject instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
// 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. username = loginMsg.getSender();
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...)
// and send back LOGIN_SUCCESS.
// TODO: Main message loop boolean registered = userManager.addUser(username,this);
// In a loop, call in.readObject(), you can separate messages by their type:
// - if it's a ChatMessage -> call handleChatMessage(msg) if (!registered) {
// - if it's a FileMessage -> call handleFileMessage(fileMsg) sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "Server", username, "Username already taken."));
// Keep looping until the connection is closed (an exception will be thrown). socket.close();
return;
}
FileManager.createUserFolders(username);
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", username, "Welcome " + username + "!"));
System.out.println(username + " logged in successfully.");
while(true) {
Object message = in.readObject();
if (message instanceof FileMessage msg) {
handleFileMessage(msg);
}
else if (message instanceof ChatMessage msg) {
handleChatMessage(msg);
}
}
} 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 e) {}
}
}
public synchronized void sendMessage(Object obj) throws IOException {
out.writeObject(obj);
out.flush();
} }
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.sendMessage(msg);
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user.
ClientSession receiver = userManager.getUser(msg.getReceiver());
if (receiver != null) {
receiver.sendMessage(msg);
sendMessage("Message sent!");
}
else {
sendMessage(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", username, "User '" + msg.getReceiver() + "' is not online."));
}
} }
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
sendMessage(new ChatMessage(MessageType.USER_LIST, "Server", username, userManager.listUsers()));
} }
} }
} }
private void handleFileMessage(FileMessage fileMsg) throws IOException { private void handleFileMessage(FileMessage fileMsg) throws IOException {
// Storing the file
var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename()); var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename());
var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), fileMsg.getFilename()); var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), fileMsg.getFilename());
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 receiver = userManager.getUser(fileMsg.getReceiver());
if (receiver != null) {
receiver.sendMessage(fileMsg);
} else {
sendMessage(new ChatMessage(
MessageType.PUBLIC_MESSAGE,
"Server", username,
"User '" + fileMsg.getReceiver() + "' is not online. File saved on server."
));
}
} }
} }