HW10 #1
@@ -1,20 +1,60 @@
|
|||||||
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 com.university.chat.Common.MessageType;
|
||||||
// chatClient created when connecting)
|
|
||||||
|
import java.io.EOFException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
|
||||||
|
public class ServerListener implements Runnable {
|
||||||
|
private final ObjectInputStream in;
|
||||||
|
private final String username;
|
||||||
|
|
||||||
|
public ServerListener(ObjectInputStream in, String username) {
|
||||||
|
this.in = in;
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
@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
|
|
||||||
// saved to disk by the server.
|
// نمایش لیست کاربران
|
||||||
} catch (Exception e){
|
if (msg.getType() == MessageType.USER_LIST) {
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("\n👥 Online Users:");
|
||||||
|
System.out.println("━━━━━━━━━━━━━━━━━━━━");
|
||||||
|
System.out.println(msg.getContent());
|
||||||
|
System.out.println("━━━━━━━━━━━━━━━━━━━━\n");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// نمایش پیام عمومی
|
||||||
|
if (msg.getType() == MessageType.PUBLIC_MESSAGE) {
|
||||||
|
System.out.println("[PUBLIC] " + msg.getSender() + ": " + msg.getContent());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// نمایش پیام خصوصی
|
||||||
|
if (msg.getType() == MessageType.PRIVATE_MESSAGE) {
|
||||||
|
System.out.println("[PRIVATE] " + msg.getSender() + ": " + msg.getContent());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// پیامهای سیستمی
|
||||||
|
System.out.println(msg.getContent());
|
||||||
|
|
||||||
|
} else if (obj instanceof FileMessage fileMsg) {
|
||||||
|
System.out.println("[FILE RECEIVED] " + fileMsg.getFilename() + " from " + fileMsg.getSender());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (EOFException e) {
|
||||||
|
System.out.println("Server disconnected.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,127 @@
|
|||||||
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.util.Scanner;
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
|
||||||
// - "/users" -> build & send a USER_LIST request
|
public class chatClient {
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
public static void main(String[] args) {
|
||||||
// (you can use TransferProgress
|
try (Socket socket = new Socket("localhost", 12345);
|
||||||
// to show progress)
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
// and send it as a FileMessage
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
Scanner scanner = new Scanner(System.in)) {
|
||||||
// Remember to flush() the output stream after writeObject().
|
|
||||||
} catch (Exception e){
|
System.out.println("Connected to server.");
|
||||||
System.out.println("command failed: " + e.getMessage());
|
|
||||||
|
// Login
|
||||||
|
System.out.print("Username: ");
|
||||||
|
String username = scanner.nextLine();
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
String finalUsername = username;
|
||||||
|
|
||||||
|
// شروع listener
|
||||||
|
new Thread(new ServerListener(in, finalUsername)).start();
|
||||||
|
|
||||||
|
boolean running = true;
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
// نمایش منو
|
||||||
|
System.out.println("\n╔════════════════════════════════╗");
|
||||||
|
System.out.println("║ Chat Menu ║");
|
||||||
|
System.out.println("╠════════════════════════════════╣");
|
||||||
|
System.out.println("║ 1. Send Public Message ║");
|
||||||
|
System.out.println("║ 2. Send Private Message ║");
|
||||||
|
System.out.println("║ 3. View Online Users ║");
|
||||||
|
System.out.println("║ 4. Send File ║");
|
||||||
|
System.out.println("║ 5. Exit ║");
|
||||||
|
System.out.println("╚════════════════════════════════╝");
|
||||||
|
System.out.print("Choose an option: ");
|
||||||
|
|
||||||
|
String choice = scanner.nextLine().trim();
|
||||||
|
|
||||||
|
switch (choice) {
|
||||||
|
case "1":
|
||||||
|
// ارسال پیام عمومی
|
||||||
|
System.out.print("Enter your message: ");
|
||||||
|
String publicMessage = scanner.nextLine();
|
||||||
|
if (!publicMessage.isEmpty()) {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, finalUsername, null, publicMessage));
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "2":
|
||||||
|
// ارسال پیام خصوصی
|
||||||
|
System.out.print("Enter recipient username: ");
|
||||||
|
String recipient = scanner.nextLine().trim();
|
||||||
|
System.out.print("Enter your message: ");
|
||||||
|
String privateMessage = scanner.nextLine();
|
||||||
|
if (!recipient.isEmpty() && !privateMessage.isEmpty()) {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, finalUsername, recipient, privateMessage));
|
||||||
|
out.flush();
|
||||||
|
} else {
|
||||||
|
System.out.println("❌ Recipient and message cannot be empty!");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "3":
|
||||||
|
// درخواست لیست کاربران
|
||||||
|
out.writeObject(new ChatMessage(MessageType.USER_LIST, finalUsername, null, null));
|
||||||
|
out.flush();
|
||||||
|
System.out.println("📋 Requesting online users...");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "4":
|
||||||
|
// ارسال فایل
|
||||||
|
System.out.print("Enter recipient username: ");
|
||||||
|
String fileRecipient = scanner.nextLine().trim();
|
||||||
|
System.out.print("Enter file path: ");
|
||||||
|
String filePath = scanner.nextLine().trim();
|
||||||
|
|
||||||
|
if (!fileRecipient.isEmpty() && !filePath.isEmpty()) {
|
||||||
|
try {
|
||||||
|
File file = new File(filePath);
|
||||||
|
if (!file.exists()) {
|
||||||
|
System.out.println("❌ File not found: " + filePath);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
byte[] data = new byte[(int) file.length()];
|
||||||
|
try (FileInputStream fis = new FileInputStream(file)) {
|
||||||
|
fis.read(data);
|
||||||
|
}
|
||||||
|
out.writeObject(new FileMessage(finalUsername, fileRecipient, file.getName(), data));
|
||||||
|
out.flush();
|
||||||
|
System.out.println("✅ File sent: " + file.getName() + " to " + fileRecipient);
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("❌ Could not send file: " + e.getMessage());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("❌ Recipient and file path cannot be empty!");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "5":
|
||||||
|
// خروج
|
||||||
|
System.out.println("👋 Goodbye!");
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGOUT, finalUsername, null, null));
|
||||||
|
out.flush();
|
||||||
|
running = false;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.out.println("❌ Invalid option! Please choose 1-5.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("❌ Could not connect to server: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
package com.university.chat.Common;
|
package com.university.chat.Common;
|
||||||
|
|
||||||
import java.io.Serializable;
|
public enum MessageType {
|
||||||
|
|
||||||
public enum MessageType implements Serializable {
|
|
||||||
LOGIN,
|
LOGIN,
|
||||||
LOGIN_SUCCESS,
|
LOGIN_SUCCESS,
|
||||||
LOGIN_FAILED,
|
LOGIN_FAILED,
|
||||||
PUBLIC_MESSAGE,
|
PUBLIC_MESSAGE,
|
||||||
PRIVATE_MESSAGE,
|
PRIVATE_MESSAGE,
|
||||||
USER_LIST,
|
USER_LIST,
|
||||||
FILE_TRANSFER
|
LOGOUT
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,27 @@
|
|||||||
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
|
private static final int PORT = 12345;
|
||||||
// broadcasting and private messaging work correctly.
|
private static final UserManager userManager = new UserManager();
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
try (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);
|
||||||
|
Thread thread = new Thread(session);
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Server error: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,70 +2,154 @@ 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 ObjectOutputStream out;
|
||||||
|
private ObjectInputStream in;
|
||||||
|
private UserManager userManager;
|
||||||
|
private Socket socket;
|
||||||
|
|
||||||
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 {
|
||||||
|
// CRITICAL: ObjectOutputStream MUST be created before ObjectInputStream
|
||||||
|
this.out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
this.out.flush();
|
||||||
|
this.in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Error setting up streams: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
|
// --- Login Step ---
|
||||||
|
Object firstObj = in.readObject();
|
||||||
|
if (!(firstObj instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
username = loginMsg.getSender();
|
||||||
// 1. Read the first object sent by the client.
|
boolean registered = userManager.addUser(username, this);
|
||||||
// 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
|
if (!registered) {
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "server", username, "Username already taken"));
|
||||||
// - 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).
|
}
|
||||||
|
|
||||||
|
FileManager.createUserFolders(username);
|
||||||
|
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "server", username, "Welcome " + username + "!"));
|
||||||
|
System.out.println("User connected: " + username);
|
||||||
|
|
||||||
|
// --- Main Message Loop ---
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
Object obj = in.readObject();
|
||||||
|
if (obj instanceof ChatMessage msg) {
|
||||||
|
handleChatMessage(msg);
|
||||||
|
} else if (obj instanceof FileMessage fileMsg) {
|
||||||
|
handleFileMessage(fileMsg);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Connection lost for: " + username);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected: " + username);
|
System.out.println("Session error for: " + 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);
|
||||||
|
System.out.println("User disconnected: " + username);
|
||||||
|
}
|
||||||
|
try { socket.close(); } catch (IOException ignored) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void handleChatMessage(ChatMessage msg) {
|
||||||
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.
|
System.out.println("[PUBLIC] " + username + ": " + msg.getContent());
|
||||||
|
for (ClientSession session : userManager.getAllSessions()) {
|
||||||
|
session.sendMessage(msg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
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) {
|
||||||
|
// Send to receiver (avoid double-send if sender == receiver)
|
||||||
|
target.sendMessage(msg);
|
||||||
|
if (!receiver.equals(username)) {
|
||||||
|
// Echo back to sender so they see their own sent message
|
||||||
|
sendMessage(msg);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sendMessage(new ChatMessage(
|
||||||
|
MessageType.PRIVATE_MESSAGE,
|
||||||
|
"server", username,
|
||||||
|
"User '" + receiver + "' is not online."
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
String list = userManager.listUsers();
|
||||||
|
sendMessage(new ChatMessage(MessageType.USER_LIST, "server", username, list));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
private void handleFileMessage(FileMessage fileMsg) {
|
||||||
// Storing the file
|
try {
|
||||||
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(recvPath, fileMsg.getData());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to save file: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
Files.write(sentPath, fileMsg.getData());
|
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
|
||||||
Files.write(recvPath, fileMsg.getData());
|
if (receiver != null) {
|
||||||
|
receiver.sendFile(fileMsg);
|
||||||
// TODO: Forward the received file-message to the destination user.
|
} else {
|
||||||
|
sendMessage(new ChatMessage(
|
||||||
|
MessageType.PRIVATE_MESSAGE,
|
||||||
|
"server", username,
|
||||||
|
"User '" + fileMsg.getReceiver() + "' is not online. File was saved on server."
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
public synchronized void sendMessage(ChatMessage msg) {
|
||||||
|
try {
|
||||||
|
out.writeObject(msg);
|
||||||
|
out.flush();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to send message to " + username);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void sendFile(FileMessage fileMsg) {
|
||||||
|
try {
|
||||||
|
out.writeObject(fileMsg);
|
||||||
|
out.flush();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to send file to " + username);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user