This commit is contained in:
2026-07-15 20:37:36 +04:30
parent 240eac0504
commit 6cf6dcc169
4 changed files with 288 additions and 64 deletions
@@ -1,20 +1,38 @@
package com.university.chat.Client;
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
import com.university.chat.Server.ClientSession;
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 incomingObject = in.readObject();
if (incomingObject instanceof ChatMessage) {
ChatMessage message = (ChatMessage) incomingObject;
System.out.println(message.getSender() + ": " + message.getContent());
} else if (incomingObject instanceof FileMessage) {
FileMessage fileMessage = (FileMessage) incomingObject;
System.out.println("[FILE RECEIVE] You received a file: '"
+ fileMessage.getFilename() + "' from " + fileMessage.getSender()
+ " (Saved on server disk).");
}
}
} catch (Exception e){
System.out.println("Disconnected from server");
System.out.println("Disconnected from server.");
}
}
}
}
@@ -1,29 +1,102 @@
package com.university.chat.Client;
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.
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
import com.university.chat.Common.MessageType;
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().
} catch (Exception e){
System.out.println("command failed: " + e.getMessage());
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
public class chatClient {
public static void main() throws IOException {
String host = "localhost";
int port = 8080;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name: ");
String username = scanner.nextLine();
try (Socket socket = new Socket(host, port);) {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ChatMessage loginMessage = new ChatMessage(MessageType.LOGIN,"Server", username, "Login successful.");
out.writeObject(loginMessage);
out.flush();
ServerListener serverListener = new ServerListener(in);
Thread listenerThread = new Thread(serverListener);
listenerThread.start();
while (true) {
try {
String input = scanner.nextLine().trim();
if (input.isEmpty()) {continue;}
if (input.startsWith("/msg ")) {
String[] parts = input.split(" ");
if (parts.length < 3) {
System.out.println("Usage: /msg <user> <text>");
continue;
}
String target = parts[1];
String msg = parts[2];
ChatMessage privateMessage = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, target, msg);
out.writeObject(privateMessage);
out.flush();
} else if (input.equalsIgnoreCase("/users")) {
ChatMessage usersList = new ChatMessage(MessageType.USER_LIST, username, "Server", "Users list request.");
out.writeObject(usersList);
out.flush();
} else if (input.startsWith("/sendfile ")) {
String[] parts = input.split(" ");
if (parts.length < 3) {
System.out.println("Usage: /sendfile <user> <text>");
continue;
}
String target = parts[1];
String filePathStr = parts[2];
File file = new File(filePathStr);
if (!file.exists() || !file.isFile()) {
System.out.println("File not found: " + filePathStr);
continue;
}
byte[] fileData = Files.readAllBytes(Path.of(filePathStr));
FileMessage fileMessage = new FileMessage(username, target, filePathStr, fileData);
out.writeObject(fileMessage);
out.flush();
System.out.println("File sent successfully.");
} else {
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, input);
out.writeObject(publicMsg);
out.flush();
}
} catch (Exception e){
System.out.println("command failed: " + e.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -1,15 +1,30 @@
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();
public static void main(String[] args) {
// TODO: Create a ServerSocket
int port = 8080;
// 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)) {
//for catching multiple clients at the same time
while (true) {
//waiting for the client and catches it when it connects
Socket socket = serverSocket.accept();
//building a client session to get the socket
ClientSession clientSession = new ClientSession(socket, userManager);
//building a thread to this client
Thread SoketThread = new Thread(clientSession);
SoketThread.start();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
@@ -2,58 +2,161 @@ 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.*;
import java.net.Socket;
import java.nio.file.Files;
import static java.lang.System.in;
import static java.lang.System.out;
public class ClientSession implements Runnable {
private Socket socket;
public ClientSession(Socket socket) {
this.socket = socket;
}
private String username;
public ClientSession(Socket socket, UserManager userManager) {
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
// and an ObjectInputStream from socket.getInputStream().
public ClientSession(Socket socket, UserManager userManager) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
} catch (IOException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
//Read the first object sent by the client
try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
// 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.
out.flush();
Object firstObject = in.readObject();
// 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 (!(firstObject instanceof ChatMessage)) {
return;
}
ChatMessage message = (ChatMessage) firstObject;
//Check it's a ChatMessage with type LOGIN
if (message.getType() != MessageType.LOGIN) {
return;
}
//Extract the username
username = message.getSender();
//Try to register the user via userManager.addUser(...)
boolean isRegistered = ChatServer.userManager.addUser(username, this);
//If the username is taken, send back LOGIN_FAILED and close the socket
if (!isRegistered) {
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "ClientSession", username, "Username is already taken."));
out.flush();
return;
}
//create the user's folders with FileManager.createUserFolders(username)
FileManager.createUserFolders(username);
//send back LOGIN_SUCCESS.
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "ClientSession", username, "Username is registered successfully!"));
out.flush();
System.out.println(username + " has been successfully registered!");
while (true) {
try {
Object receivedObject = in.readObject();
if (receivedObject instanceof ChatMessage) {
handleChatMessage((ChatMessage) receivedObject);
} else if (receivedObject instanceof FileMessage) {
handleFileMessage((FileMessage) receivedObject);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
break;
}
}
} catch (Exception e) {
System.out.println("Disconnected: " + username);
out.println("Disconnected: " + username);
} finally {
// TODO: Remove the user from UserManager so they no longer
// receive broadcasts or appear in users list
if (!username.equals("unknown")) {
ChatServer.userManager.removeUser(username);
out.println(username + " removed!");
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleChatMessage(ChatMessage msg) throws IOException {
switch (msg.getType()) {
//to Broadcast this message to every connected client.
case PUBLIC_MESSAGE -> {
// TODO: Broadcast this message to every connected client.
String sender = msg.getSender();
String content = msg.getContent();
for (ClientSession session : ChatServer.userManager.getAllSessions()) {
try {
ObjectOutputStream out = new ObjectOutputStream(session.socket.getOutputStream());
out.writeObject(session);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("[PUBLIC] " + msg.getSender() + ": " + msg.getContent());
}
//to Forward this message to the receiver user.
case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user.
String receiver = msg.getReceiver();
ClientSession receiverSession = ChatServer.userManager.getUser(receiver);
if (receiverSession != null) {
try {
ObjectOutputStream out = new ObjectOutputStream(receiverSession.socket.getOutputStream());
out.writeObject(receiverSession);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
} else {
ChatMessage errorMessage = new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", msg.getSender(), "User" + receiver + " not found.");
ObjectOutputStream out = new ObjectOutputStream(this.socket.getOutputStream());
out.writeObject(errorMessage);
out.flush();
}
}
//to Reply to the requester with the list of online users.
case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
String onlineUsers = ChatServer.userManager.listUsers();
ChatMessage message = new ChatMessage(MessageType.USER_LIST, "Server", msg.getSender(), onlineUsers);
ObjectOutputStream out = new ObjectOutputStream(this.socket.getOutputStream());
out.writeObject(message);
out.flush();
}
}
}
@@ -66,6 +169,21 @@ public class ClientSession implements Runnable {
Files.write(sentPath, fileMsg.getData());
Files.write(recvPath, fileMsg.getData());
// TODO: Forward the received file-message to the destination user.
String receiverName = fileMsg.getReceiver();
ClientSession receiverSession = ChatServer.userManager.getUser(receiverName);
if (receiverSession != null) {
try {
ObjectOutputStream out = new ObjectOutputStream(receiverSession.socket.getOutputStream());
out.writeObject(receiverSession);
out.flush();
System.out.println("[FILE] " + fileMsg.getFilename() + " from " + fileMsg.getSender() + " to " + receiverName + " sent.");
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("[FILE] user " + receiverName + " is not online. File saved on server but not sent.");
}
}
}