workshop 10 codes

This commit is contained in:
2026-06-26 12:15:06 +03:30
parent 240eac0504
commit 08ef4ebd28
5 changed files with 247 additions and 9 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
</list> </list>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_23" project-jdk-name="23 (2)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>
@@ -1,10 +1,21 @@
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;
public class ServerListener implements Runnable{ public class ServerListener implements Runnable{
// TODO: store the ObjectInputStream from the user socket // TODO: store the ObjectInputStream from the user socket
// (this should be the same input stream the // (this should be the same input stream the
// chatClient created when connecting) // chatClient created when connecting)
private final ObjectInputStream in;
public ServerListener(ObjectInputStream in) {
this.in = in;
}
@Override @Override
public void run() { public void run() {
try { try {
@@ -13,8 +24,44 @@ public class ServerListener implements Runnable{
// - if it's a FileMessage -> print that a file was received // - if it's a FileMessage -> print that a file was received
// (filename + sender), it's already // (filename + sender), it's already
// saved to disk by the server. // saved to disk by the server.
while (true) {
Object obj = in.readObject();
if (obj instanceof ChatMessage msg) {
handleChatMessage(msg);
} else if (obj instanceof FileMessage fileMsg) {
System.out.println("\n[File received] '" + fileMsg.getFilename()
+ "' from " + fileMsg.getSender()
+ " (saved to your received folder).");
}
}
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
} }
private void handleChatMessage(ChatMessage msg) {
switch (msg.getType()) {
case LOGIN_SUCCESS ->
System.out.println("[Server] " + msg.getContent());
case LOGIN_FAILED -> {
System.out.println("[Server] Login failed: " + msg.getContent());
System.exit(1);
}
case PUBLIC_MESSAGE ->
System.out.println("[Public] " + msg.getSender() + ": " + msg.getContent());
case PRIVATE_MESSAGE ->
System.out.println("[Private] " + msg.getSender() + " -> " + msg.getReceiver()
+ ": " + msg.getContent());
case USER_LIST ->
System.out.println("[Online users] " + msg.getContent());
default ->
System.out.println("[Server] " + msg.getContent());
}
}
} }
@@ -1,7 +1,22 @@
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.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
public class chatClient { public class chatClient {
public static void main() { private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 12345;
public static void main(String[] args) {
// TODO: Connecting to the server // TODO: Connecting to the server
// 1. Create a socket and connect to the server // 1. Create a socket and connect to the server
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in) // 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
@@ -9,7 +24,24 @@ public class chatClient {
// 2. Get the username, and send a LOGIN ChatMessage with that username // 2. Get the username, and send a LOGIN ChatMessage with that username
// 3. Start a new Thread running a ServerListener(in) so incoming // 3. Start a new Thread running a ServerListener(in) so incoming
// messages are handled concurrently. // messages are handled concurrently.
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
try {
Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
System.out.println("Connected to server at " + SERVER_HOST + ":" + SERVER_PORT);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
System.out.print("Enter your username: ");
String username = console.readLine().trim();
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
out.flush();
Thread listenerThread = new Thread(new ServerListener(in));
listenerThread.setDaemon(true);
listenerThread.start();
System.out.println("Commands: /msg <user> <text> | /users | /sendfile <user> <path>");
while (true){ while (true){
try { try {
// TODO: Program loop — read a line from the console and act on it: // TODO: Program loop — read a line from the console and act on it:
@@ -21,9 +53,67 @@ public class chatClient {
// and send it as a FileMessage // and send it as a FileMessage
// - anything else -> send a PUBLIC_MESSAGE // - anything else -> send a PUBLIC_MESSAGE
// Remember to flush() the output stream after writeObject(). // Remember to flush() the output stream after writeObject().
String line = console.readLine();
if (line == null) break;
line = line.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 text = parts[2];
out.writeObject(new ChatMessage(
MessageType.PRIVATE_MESSAGE, username, receiver, 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 <username> <filepath>");
continue;
}
String receiver = parts[1];
String filepath = parts[2];
var path = Paths.get(filepath);
if (!Files.exists(path)) {
System.out.println("File not found: " + filepath);
continue;
}
byte[] fileData = Files.readAllBytes(path);
String filename = path.getFileName().toString();
TransferProgress progress = new TransferProgress(fileData.length);
progress.update(fileData.length); // single-shot since it's already in memory
out.writeObject(new FileMessage(username, receiver, filename, fileData));
out.flush();
System.out.println("File '" + filename + "' sent to " + receiver + ".");
} else {
out.writeObject(new ChatMessage(
MessageType.PUBLIC_MESSAGE, username, null, line));
out.flush();
}
} catch (Exception e){ } 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 server: " + e.getMessage());
} }
} }
}
@@ -1,15 +1,36 @@
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) // TODO: declare a single shared UserManager instance (static final)
// This MUST be shared by all ClientSession threads so that // This MUST be shared by all ClientSession threads so that
// broadcasting and private messaging work correctly. // broadcasting and private messaging work correctly.
private static final int PORT = 12345;
private static final UserManager userManager = new UserManager();
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket // TODO: Create a ServerSocket
// TODO: In an infinite loop: // TODO: In an infinite loop:
// accept an incoming client connection // accept an incoming client connection
// make a new thread running ClientSession for each user. // make a new thread running ClientSession for each user.
System.out.println("Server starting on port " + PORT + "...");
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening for connections.");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getInetAddress());
ClientSession session = new ClientSession(clientSocket, userManager);
Thread thread = new Thread(session);
thread.start();
}
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
}
} }
} }
@@ -2,18 +2,35 @@ 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.net.Socket; import java.net.Socket;
import java.nio.file.Files; import java.nio.file.Files;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ClientSession implements Runnable { public class ClientSession implements Runnable {
private String username; private String username;
private final Socket socket;
private final 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() // TODO : Create an ObjectOutputStream from socket.getOutputStream()
// and an ObjectInputStream from socket.getInputStream(). // 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.out.println("Failed to set up streams: " + e.getMessage());
}
} }
@Override @Override
@@ -34,32 +51,87 @@ public class ClientSession implements Runnable {
// - if it's a ChatMessage -> call handleChatMessage(msg) // - if it's a ChatMessage -> call handleChatMessage(msg)
// - if it's a FileMessage -> call handleFileMessage(fileMsg) // - if it's a FileMessage -> call handleFileMessage(fileMsg)
// Keep looping until the connection is closed (an exception will be thrown). // Keep looping until the connection is closed (an exception will be thrown).
Object firstObject = in.readObject();
if (!(firstObject instanceof ChatMessage loginMsg)
|| loginMsg.getType() != MessageType.LOGIN) {
socket.close();
return;
}
username = loginMsg.getSender();
if (!userManager.addUser(username, this)) {
sendMessage(new ChatMessage(
MessageType.LOGIN_FAILED, "Server", username,
"Username '" + username + "' is already taken. Please reconnect with a different name."));
socket.close();
return;
}
FileManager.createUserFolders(username);
sendMessage(new ChatMessage(
MessageType.LOGIN_SUCCESS, "Server", username,
"Welcome, " + username + "! You are now connected."));
System.out.println(username + " logged in.");
while (true) {
Object obj = in.readObject();
if (obj instanceof ChatMessage msg) {
handleChatMessage(msg);
} else if (obj instanceof FileMessage fileMsg) {
handleFileMessage(fileMsg);
}
}
} 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 // TODO: Remove the user from UserManager so they no longer
// receive broadcasts or appear in users list // receive broadcasts or appear in users list
if (username != null) {
userManager.removeUser(username);
System.out.println(username + " removed from user list.");
}
try { socket.close(); } catch (IOException ignored) {}
} }
} }
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. // 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. // TODO: Forward this message to the receiver user.
ClientSession receiver = userManager.getUser(msg.getReceiver());
if (receiver != null) {
receiver.sendMessage(msg);
sendMessage(msg);
} 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. // TODO: Reply to the requester with the list of online users.
String userList = userManager.listUsers();
sendMessage(new ChatMessage(
MessageType.USER_LIST, "Server", username, userList));
} }
} }
} }
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());
@@ -67,5 +139,13 @@ public class ClientSession implements Runnable {
Files.write(recvPath, fileMsg.getData()); Files.write(recvPath, fileMsg.getData());
// TODO: Forward the received file-message to the destination user. // 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 not delivered."));
}
} }
} }