1 Commits
Author SHA1 Message Date
Reza d6b7215667 complete 2026-06-19 13:44:24 +03:30
4 changed files with 192 additions and 66 deletions
@@ -1,18 +1,32 @@
package com.university.chat.Client; package com.university.chat.Client;
public class ServerListener implements Runnable{ import com.university.chat.Common.ChatMessage;
// TODO: store the ObjectInputStream from the user socket import com.university.chat.Common.FileMessage;
// (this should be the same input stream the import java.io.ObjectInputStream;
// chatClient created when connecting)
public class ServerListener implements Runnable{
private final ObjectInputStream in;
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 msg) {
// (filename + sender), it's already if (msg.getType() == com.university.chat.Common.MessageType.USER_LIST) {
// saved to disk by the server. System.out.println("Online users: " + msg.getContent());
} else {
System.out.println(msg.getSender() + ": " + msg.getContent());
}
} else if (obj instanceof FileMessage fileMsg) {
System.out.println("File received: " + fileMsg.getFilename()
+ " from " + fileMsg.getSender());
}
}
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
@@ -1,29 +1,81 @@
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 import java.io.IOException;
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in) import java.io.ObjectInputStream;
// from the socket's streams — output FIRST, then input. import java.io.ObjectOutputStream;
// 2. Get the username, and send a LOGIN ChatMessage with that username import java.net.Socket;
// 3. Start a new Thread running a ServerListener(in) so incoming import java.nio.file.Files;
// messages are handled concurrently. import java.nio.file.Path;
import java.util.Scanner;
while (true){ public class chatClient {
try { public static void main(String[] args) {
// TODO: Program loop — read a line from the console and act on it: String serverAddress = "localhost";
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE int serverPort = 12345;
// - "/users" -> build & send a USER_LIST request
// - "/sendfile <user> <path>" -> read the file into a byte[] try (Socket socket = new Socket(serverAddress, serverPort);
// (you can use TransferProgress ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
// to show progress) ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
// and send it as a FileMessage Scanner console = new Scanner(System.in)) {
// - anything else -> send a PUBLIC_MESSAGE
// Remember to flush() the output stream after writeObject(). System.out.print("Enter username: ");
} catch (Exception e){ String username = console.nextLine();
System.out.println("command failed: " + e.getMessage()); out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
out.flush();
ChatMessage response = (ChatMessage) in.readObject();
if (response.getType() == MessageType.LOGIN_FAILED) {
System.out.println("Login failed: " + response.getContent());
return;
} }
System.out.println("Connected as " + username);
Thread listener = new Thread(new ServerListener(in));
listener.start();
while (true) {
try {
String line = console.nextLine();
if (line.startsWith("/msg ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /msg <user> <message>");
continue;
}
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]));
}
else if (line.equals("/users")) {
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, null, null));
}
else if (line.startsWith("/sendfile ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /sendfile <user> <filepath>");
continue;
}
try {
byte[] data = Files.readAllBytes(Path.of(parts[2]));
out.writeObject(new FileMessage(username, parts[1],
Path.of(parts[2]).getFileName().toString(), data));
}
catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
}
else {
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line));
}
out.flush();
}
catch (Exception e) {
System.out.println("command failed: " + e.getMessage());
}
}
} catch (Exception e) {
System.out.println("Connection closed: " + e.getMessage());
} }
} }
} }
@@ -1,15 +1,20 @@
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) throws Exception {
// TODO: Create a ServerSocket int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
// TODO: In an infinite loop: while (true) {
// accept an incoming client connection Socket clientSocket = serverSocket.accept();
// make a new thread running ClientSession for each user. ClientSession session = new ClientSession(clientSocket, userManager);
new Thread(session).start();
}
} }
} }
@@ -2,70 +2,125 @@ 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.EOFException;
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) {
closeEverything();
}
} }
@Override @Override
public void run() { public void run() {
try { try {ChatMessage loginMsg = (ChatMessage) in.readObject();
if (loginMsg.getType() != MessageType.LOGIN) {
closeEverything();
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.
// TODO: Main message loop username = loginMsg.getSender();
// In a loop, call in.readObject(), you can separate messages by their type: if (!userManager.addUser(username, this)) {
// - 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) { out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", username, "Username already taken"));
out.flush();
closeEverything();
return;
}
FileManager.createUserFolders(username);
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", username, "Welcome!"));
out.flush();
Object obj;
while ((obj = in.readObject()) != null) {
if (obj instanceof ChatMessage msg) {
handleChatMessage(msg);
} else if (obj instanceof FileMessage fileMsg) {
handleFileMessage(fileMsg);
}
}
}
catch (EOFException 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) userManager.removeUser(username);
// receive broadcasts or appear in users list closeEverything();
} }
} }
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()) {
if (!session.equals(this)) {
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);
}
} }
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", username, list);
sendMessage(reply);
} }
} }
} }
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.sendFile(fileMsg);
}
}
public void sendMessage(ChatMessage msg) throws IOException {
out.writeObject(msg);
out.flush();
}
public void sendFile(FileMessage fileMsg) throws IOException {
out.writeObject(fileMsg);
out.flush();
}
private void closeEverything() {
try { if (out != null) out.close(); } catch (IOException ignored) {}
try { if (in != null) in.close(); } catch (IOException ignored) {}
try { if (socket != null) socket.close(); } catch (IOException ignored) {}
} }
} }