Assignment-10
This commit is contained in:
@@ -1,18 +1,32 @@
|
||||
package com.university.chat.Client;
|
||||
|
||||
import com.university.chat.Common.ChatMessage;
|
||||
import com.university.chat.Common.FileMessage;
|
||||
|
||||
import java.io.ObjectInputStream;
|
||||
|
||||
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)
|
||||
private final ObjectInputStream in;
|
||||
|
||||
public ServerListener(ObjectInputStream in) {
|
||||
this.in = in;
|
||||
}
|
||||
|
||||
@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.
|
||||
while (true) {
|
||||
Object receivedObject = in.readObject();
|
||||
|
||||
if (receivedObject instanceof ChatMessage) {
|
||||
ChatMessage chatMsg = (ChatMessage) receivedObject;
|
||||
System.out.println(chatMsg.getSender() + ": " + chatMsg.getContent());
|
||||
} else if (receivedObject instanceof FileMessage) {
|
||||
FileMessage fileMsg = (FileMessage) receivedObject;
|
||||
System.out.println("[System] File received: " + fileMsg.getFilename() +
|
||||
" sent by " + fileMsg.getSender() + ".");
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
|
||||
@@ -1,26 +1,109 @@
|
||||
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.*;
|
||||
import java.net.Socket;
|
||||
import java.util.Scanner;
|
||||
|
||||
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.
|
||||
private static final String SERVER_HOST = "127.0.0.1";
|
||||
private static final int SERVER_PORT = 5000;
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
Socket socket;
|
||||
ObjectOutputStream out;
|
||||
ObjectInputStream in;
|
||||
String username;
|
||||
|
||||
try {
|
||||
System.out.println("Connecting to server at " + SERVER_HOST + ":" + SERVER_PORT + "...");
|
||||
socket = new Socket(SERVER_HOST, SERVER_PORT);
|
||||
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
out.flush();
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
|
||||
System.out.print("Enter your username: ");
|
||||
username = scanner.nextLine().trim();
|
||||
|
||||
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, "SERVER", "");
|
||||
out.writeObject(loginMsg);
|
||||
out.flush();
|
||||
|
||||
ServerListener listener = new ServerListener(in);
|
||||
Thread listenerThread = new Thread(listener);
|
||||
listenerThread.setDaemon(true);
|
||||
listenerThread.start();
|
||||
|
||||
System.out.println("Logged in successfully! You can now type your message.");
|
||||
} catch (IOException e) {
|
||||
System.err.println("Could not connect to server: " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
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().
|
||||
String line = scanner.nextLine().trim();
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
if (line.startsWith("/msg")) {
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length < 3) {
|
||||
System.out.println("Usage: /msg <username> <message>");
|
||||
continue;
|
||||
}
|
||||
String receiver = parts[1];
|
||||
String message = parts[2];
|
||||
|
||||
ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, receiver, message);
|
||||
out.writeObject(privateMsg);
|
||||
|
||||
System.out.println("[To " + receiver + "]: " + message);
|
||||
|
||||
} else if (line.trim().equals("/users")) {
|
||||
ChatMessage listMsg = new ChatMessage(MessageType.USER_LIST, username, "SERVER", "");
|
||||
out.writeObject(listMsg);
|
||||
|
||||
} else if (line.startsWith("/sendfile")) {
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length < 3) {
|
||||
System.out.println("Usage: /sendfile <username> <filepath>");
|
||||
continue;
|
||||
}
|
||||
String receiver = parts[1];
|
||||
String filePath = parts[2];
|
||||
|
||||
File file = new File(filePath);
|
||||
if (!file.exists()) {
|
||||
System.out.println("File does not exist: " + filePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
long fileSize = file.length();
|
||||
byte[] fileData = new byte[(int) fileSize];
|
||||
|
||||
try (FileInputStream fis = new FileInputStream(file)) {
|
||||
fis.read(fileData);
|
||||
}
|
||||
|
||||
TransferProgress progress = new TransferProgress(fileSize);
|
||||
progress.update(fileSize);
|
||||
|
||||
FileMessage fileMsg = new FileMessage(username, receiver, file.getName(), fileData);
|
||||
out.writeObject(fileMsg);
|
||||
System.out.println(file.getName() + " Sent successfully.");
|
||||
|
||||
} else {
|
||||
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "ALL", line);
|
||||
out.writeObject(publicMsg);
|
||||
}
|
||||
|
||||
out.flush();
|
||||
|
||||
} catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
}
|
||||
|
||||
@@ -1,15 +1,34 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
|
||||
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 final UserManager userManager = new UserManager();
|
||||
private static final int PORT = 5000;
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO: Create a ServerSocket
|
||||
System.out.println("Initializing Chat Server on port " + PORT + "...");
|
||||
|
||||
// TODO: In an infinite loop:
|
||||
// accept an incoming client connection
|
||||
// make a new thread running ClientSession for each user.
|
||||
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
|
||||
System.out.println("Server successfully connected to port. Waiting for clients...");
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
System.out.println("Connection established with: " + clientSocket.getRemoteSocketAddress());
|
||||
|
||||
ClientSession clientSession = new ClientSession(clientSocket, userManager);
|
||||
Thread sessionThread = new Thread(clientSession);
|
||||
sessionThread.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to accept a specific client connection: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Critical Server Error: Could not listen on port " + PORT);
|
||||
System.err.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,70 +2,127 @@ package com.university.chat.Server;
|
||||
|
||||
import com.university.chat.Common.ChatMessage;
|
||||
import com.university.chat.Common.FileMessage;
|
||||
import com.university.chat.Common.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
|
||||
public class ClientSession implements Runnable {
|
||||
|
||||
private final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private ObjectOutputStream out;
|
||||
private ObjectInputStream in;
|
||||
private String username;
|
||||
|
||||
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.out.flush();
|
||||
this.in = new ObjectInputStream(socket.getInputStream());
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error initializing streams for session: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Object firstObject = in.readObject();
|
||||
|
||||
// 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.
|
||||
if (firstObject instanceof ChatMessage loginMsg && loginMsg.getType() == MessageType.LOGIN) {
|
||||
this.username = loginMsg.getSender();
|
||||
|
||||
// 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).
|
||||
if (userManager.addUser(username, this)) {
|
||||
FileManager.createUserFolders(username);
|
||||
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "SERVER", username, "Login successful."));
|
||||
System.out.println("[Server] User logged in: " + username);
|
||||
} else {
|
||||
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "SERVER", username, "Username is already taken."));
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
Object receivedObject = in.readObject();
|
||||
|
||||
if (receivedObject instanceof ChatMessage) {
|
||||
handleChatMessage((ChatMessage) receivedObject);
|
||||
} else if (receivedObject instanceof FileMessage) {
|
||||
handleFileMessage((FileMessage) receivedObject);
|
||||
}
|
||||
}
|
||||
} 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
|
||||
if (username != null) {
|
||||
if (userManager.getUser(username) == this) {
|
||||
userManager.removeUser(username);
|
||||
System.out.println("[Server] Safely removed active user: " + username);
|
||||
}
|
||||
}
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||
switch (msg.getType()) {
|
||||
case PUBLIC_MESSAGE -> {
|
||||
// TODO: Broadcast this message to every connected client.
|
||||
for (ClientSession session : userManager.getAllSessions()) {
|
||||
session.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
ClientSession recipient = userManager.getUser(msg.getReceiver());
|
||||
if (recipient != null) {
|
||||
recipient.sendMessage(msg);
|
||||
} else {
|
||||
sendMessage(new ChatMessage(MessageType.PUBLIC_MESSAGE, "SERVER", username, "User " + msg.getReceiver() + " is offline."));
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
String activeUsers = userManager.listUsers();
|
||||
ChatMessage listMsg = new ChatMessage(MessageType.USER_LIST, "SERVER", username, activeUsers);
|
||||
sendMessage(listMsg);
|
||||
}
|
||||
default -> System.out.println("Unknown ChatMessage type received.");
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
ClientSession recipient = userManager.getUser(fileMsg.getReceiver());
|
||||
if (recipient != null) {
|
||||
recipient.sendMessage(fileMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void sendMessage(Object msg) {
|
||||
try {
|
||||
if (out != null) {
|
||||
out.writeObject(msg);
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to send packet to " + username + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user