Files
HW-10-Socket-Programming/src/main/java/com/university/chat/Server/ClientSession.java
T
2026-07-07 00:43:01 +03:30

140 lines
5.5 KiB
Java

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.in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
System.out.println("Failed to open streams: " + e.getMessage());
}
}
@Override
public void run() {
try {
// 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.
Object first = in.readObject();
if (!(first instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "server", null, "Expected LOGIN message"));
socket.close();
return;
}
username = loginMsg.getSender();
if (!userManager.addUser(username, this)) {
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "server", username, "Username already taken"));
socket.close();
return;
}
FileManager.createUserFolders(username);
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "server", username, "Welcome, " + username + "!"));
// 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).
while (true) {
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("Disconnected: " + username);
} finally {
// TODO: Remove the user from UserManager so they no longer
// receive broadcasts or appear in users list
if (username != null) {
userManager.removeUser(username);
}
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 {
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 receiver = userManager.getUser(msg.getReceiver());
if (receiver != null) {
receiver.sendMessage(msg);
} else {
sendMessage(new ChatMessage(MessageType.PRIVATE_MESSAGE, "server", username,
"User '" + msg.getReceiver() + "' is not online."));
}
}
case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
sendMessage(new ChatMessage(MessageType.USER_LIST, "server", username, userManager.listUsers()));
}
default -> {
}
}
}
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 receiver = userManager.getUser(fileMsg.getReceiver());
if (receiver != null) {
receiver.sendMessage(fileMsg);
}
}
}