feat : implement chat message features #1

Open
amirmt wants to merge 1 commits from develop into main
4 changed files with 301 additions and 73 deletions
@@ -1,19 +1,35 @@
package com.university.chat.Client;
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)
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
import java.io.ObjectInputStream;
public class ServerListener implements Runnable
{
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.
} catch (Exception e){
try
{
while (true)
{
Object obj = in.readObject();
if (obj instanceof ChatMessage msg)
System.out.println(msg.getSender() + ": " + msg.getContent());
else if (obj instanceof FileMessage fileMsg)
System.out.println("File received from " + fileMsg.getSender() + " : " + fileMsg.getFilename());
}
}
catch (Exception e)
{
System.out.println("Disconnected from server");
}
}
@@ -1,29 +1,133 @@
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;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Scanner;
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());
public class chatClient
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("localhost", 5000);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Scanner scanner = new Scanner(System.in);
System.out.print("Username: ");
String username = scanner.nextLine();
ChatMessage login = new ChatMessage(MessageType.LOGIN, username, null, "");
out.writeObject(login);
out.flush();
new Thread(new ServerListener(in)).start();
while (true)
{
try
{
String line = scanner.nextLine();
if (line.startsWith("/msg "))
{
String[] parts = line.split(" ", 3);
if (parts.length < 3)
continue;
ChatMessage msg =
new ChatMessage(
MessageType.PRIVATE_MESSAGE,
username,
parts[1],
parts[2]
);
out.writeObject(msg);
out.flush();
}
else if (line.equals("/users"))
{
ChatMessage msg =
new ChatMessage(
MessageType.USER_LIST,
username,
null,
""
);
out.writeObject(msg);
out.flush();
}
else if (line.startsWith("/sendfile "))
{
String[] parts = line.split(" ", 3);
if (parts.length < 3)
continue;
String receiver = parts[1];
File file = new File(parts[2]);
byte[] data = Files.readAllBytes(file.toPath());
TransferProgress progress = new TransferProgress(data.length);
progress.update(data.length);
FileMessage fileMessage =
new FileMessage(
username,
receiver,
file.getName(),
data
);
out.writeObject(fileMessage);
out.flush();
}
else
{
ChatMessage msg =
new ChatMessage(
MessageType.PUBLIC_MESSAGE,
username,
null,
line
);
out.writeObject(msg);
out.flush();
}
}
catch (Exception e)
{
System.out.println("command failed: " + e.getMessage());
}
}
}
catch (Exception e)
{
// just for debugging
e.printStackTrace();
}
}
}
}
@@ -1,15 +1,34 @@
package com.university.chat.Server;
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.
import java.net.ServerSocket;
import java.net.Socket;
public static void main(String[] args) {
// TODO: Create a ServerSocket
public class ChatServer
{
private static final UserManager USER_MANAGER = new UserManager();
// TODO: In an infinite loop:
// accept an incoming client connection
// make a new thread running ClientSession for each user.
public static void main(String[] args)
{
int port = 5000;
try (ServerSocket serverSocket = new ServerSocket(port))
{
System.out.println("Server started on port " + port);
while (true)
{
Socket socket = serverSocket.accept();
ClientSession session = new ClientSession(socket, USER_MANAGER);
new Thread(session).start();
}
}
catch (Exception e)
{
// just for debugging
e.printStackTrace();
}
}
}
}
@@ -7,53 +7,133 @@ import java.io.IOException;
import java.net.Socket;
import java.nio.file.Files;
import com.university.chat.Common.MessageType;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ClientSession implements Runnable {
private String username;
private final Socket socket;
private final UserManager userManager;
public ClientSession(Socket socket, UserManager userManager) {
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
// and an ObjectInputStream from socket.getInputStream().
private ObjectInputStream in;
private ObjectOutputStream out;
public ClientSession(Socket socket, UserManager userManager)
{
this.socket = socket;
this.userManager = userManager;
try
{
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public void run() {
try {
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)
{
socket.close();
return;
}
// 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).
username = loginMsg.getSender();
} catch (Exception e) {
if (!userManager.addUser(username, this))
{
sendObject(
new ChatMessage(
MessageType.LOGIN_FAILED,
"SERVER",
username,
"Username already exists"
)
);
socket.close();
return;
}
FileManager.createUserFolders(username);
sendObject(
new ChatMessage(
MessageType.LOGIN_SUCCESS,
"SERVER",
username,
"Login successful"
)
);
System.out.println(username + " connected");
while (true)
{
Object obj = in.readObject();
if (obj instanceof ChatMessage chatMsg)
handleChatMessage(chatMsg);
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
}
finally
{
if (username != null) {
userManager.removeUser(username);
}
}
}
private void handleChatMessage(ChatMessage msg) throws IOException {
switch (msg.getType()) {
case PUBLIC_MESSAGE -> {
// TODO: Broadcast this message to every connected client.
switch (msg.getType())
{
case PUBLIC_MESSAGE ->
{
for (ClientSession session : userManager.getAllSessions())
session.sendObject(msg);
}
case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user.
case PRIVATE_MESSAGE ->
{
ClientSession receiver = userManager.getUser(msg.getReceiver());
if (receiver != null)
receiver.sendObject(msg);
}
case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
case USER_LIST ->
{
ChatMessage response =
new ChatMessage(
MessageType.USER_LIST,
"SERVER",
username,
userManager.listUsers()
);
sendObject(response);
}
}
}
@@ -66,6 +146,15 @@ 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.
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
if (receiver != null)
receiver.sendObject(fileMsg);
}
public synchronized void sendObject(Object obj) throws IOException
{
out.writeObject(obj);
out.flush();
}
}