This commit is contained in:
2026-06-22 19:54:05 +03:30
parent 240eac0504
commit 564cfd069f
4 changed files with 181 additions and 67 deletions
@@ -1,20 +1,33 @@
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
// chatClient created when connecting) import java.io.ObjectInputStream;
public class ServerListener implements Runnable {
private 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) {
// (filename + sender), it's already ChatMessage msg = (ChatMessage) obj;
// saved to disk by the server. System.out.println(msg.getSender() + ": " + msg.getContent());
} catch (Exception e){ } else if (obj instanceof FileMessage) {
FileMessage fileMsg = (FileMessage) obj;
System.out.println("File received: " + fileMsg.getFilename() + " from " + fileMsg.getSender());
}
}
} catch (Exception e) {
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
} }
} }
@@ -1,29 +1,72 @@
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.File;
try { import java.io.ObjectInputStream;
// TODO: Program loop — read a line from the console and act on it: import java.io.ObjectOutputStream;
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE import java.net.Socket;
// - "/users" -> build & send a USER_LIST request import java.nio.file.Files;
// - "/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 public static void main(String[] args) {
// - anything else -> send a PUBLIC_MESSAGE try {
// Remember to flush() the output stream after writeObject(). Scanner scanner = new Scanner(System.in);
} catch (Exception e){ Socket socket = new Socket("localhost", 8080);
System.out.println("command failed: " + e.getMessage());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
System.out.print("Enter your username: ");
String username = scanner.nextLine();
out.writeObject(new ChatMessage(MessageType.LOGIN, username, "Server", ""));
out.flush();
Thread listenerThread = new Thread(new ServerListener(in));
listenerThread.start();
while (true) {
String input = scanner.nextLine();
if (input.startsWith("/msg ")) {
String[] parts = input.split(" ", 3);
if (parts.length == 3) {
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]));
out.flush();
}
} else if (input.equals("/users")) {
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, "Server", ""));
out.flush();
} else if (input.startsWith("/sendfile ")) {
String[] parts = input.split(" ", 3);
if (parts.length == 3) {
String receiver = parts[1];
String filepath = parts[2];
File file = new File(filepath);
if (file.exists() && file.isFile()) {
byte[] fileData = Files.readAllBytes(file.toPath());
TransferProgress progress = new TransferProgress(fileData.length);
progress.update(fileData.length);
out.writeObject(new FileMessage(username, receiver, file.getName(), fileData));
out.flush();
} else {
System.out.println("File not found or invalid path.");
}
}
} else {
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "All", input));
out.flush();
}
} }
} catch (Exception e) {
System.out.println("command failed: " + e.getMessage());
} }
} }
} }
@@ -1,15 +1,22 @@
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)
// This MUST be shared by all ClientSession threads so that private static final UserManager userManager = new UserManager();
// broadcasting and private messaging work correctly.
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server started on port 8080");
// 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();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
} }
@@ -2,70 +2,121 @@ 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() this.socket = socket;
// and an ObjectInputStream from socket.getInputStream(). this.userManager = userManager;
try {
this.out = new ObjectOutputStream(socket.getOutputStream());
this.out.flush();
this.in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
} }
@Override @Override
public void run() { public void run() {
try { try {
Object firstObject = in.readObject();
if (firstObject instanceof ChatMessage) {
ChatMessage loginMsg = (ChatMessage) firstObject;
if (loginMsg.getType() == MessageType.LOGIN) {
this.username = loginMsg.getSender();
if (!userManager.addUser(this.username, this)) {
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", this.username, "Username already taken"));
out.flush();
socket.close();
return;
}
FileManager.createUserFolders(this.username);
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", this.username, "Login successful"));
out.flush();
}
}
// TODO: Welcome the user (login step) while (true) {
// 1. Read the first object sent by the client. Object msg = in.readObject();
// 2. Check it's a ChatMessage with type LOGIN. if (msg instanceof ChatMessage) {
// 3. Extract the username. handleChatMessage((ChatMessage) msg);
// 4. Try to register the user via userManager.addUser(...). } else if (msg instanceof FileMessage) {
// 5. If the username is taken, send back LOGIN_FAILED and close the socket. handleFileMessage((FileMessage) msg);
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...) }
// and send back LOGIN_SUCCESS. }
// 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).
} 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 {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
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.username.equals(this.username)) {
session.sendMessage(msg);
}
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user. ClientSession receiverSession = userManager.getUser(msg.getReceiver());
if (receiverSession != null) {
receiverSession.sendMessage(msg);
}
} }
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users. String users = userManager.listUsers();
sendMessage(new ChatMessage(MessageType.USER_LIST, "Server", this.username, users));
} }
} }
} }
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 receiverSession = userManager.getUser(fileMsg.getReceiver());
if (receiverSession != null) {
receiverSession.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();
} }
} }