3 Commits
Author SHA1 Message Date
Aryan 12ff49473f Merge pull request 'develop' (#1) from develop into main
Reviewed-on: Mobina/HW-10-Socket-Programming#1

100 / 100
2026-07-21 18:16:14 +00:00
Mobina 075c02fefe correcting chatClient 2026-07-18 00:04:31 +03:30
Mobina daa9451984 develop 2026-06-20 00:17:32 +03:30
4 changed files with 284 additions and 29 deletions
@@ -1,18 +1,44 @@
package com.university.chat.Client; package com.university.chat.Client;
import com.university.chat.Common.ChatMessage;
import com.university.chat.Common.FileMessage;
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 {
// 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
// (filename + sender), it's already if(obj instanceof ChatMessage msg){
// saved to disk by the server. System.out.println(
msg.getSender()
+ ": "
+ msg.getContent()
);
}
else if(obj instanceof FileMessage file){
System.out.println(
"File received from "
+ file.getSender()
+ ": "
+ file.getFilename()
);
}
}
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
@@ -1,29 +1,135 @@
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.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Scanner;
public class chatClient { public class chatClient {
public static void main() {
// TODO: Connecting to the server public static void main(String[] args) {
// 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){
try { try {
// TODO: Program loop — read a line from the console and act on it: Socket socket = new Socket("localhost", 8080);
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
// - "/users" -> build & send a USER_LIST request ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
// - "/sendfile <user> <path>" -> read the file into a byte[]
// (you can use TransferProgress ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
// to show progress)
// and send it as a FileMessage Scanner scanner = new Scanner(System.in);
// - anything else -> send a PUBLIC_MESSAGE
// Remember to flush() the output stream after writeObject(). System.out.print("Enter username: ");
} catch (Exception e){ String username = scanner.nextLine();
System.out.println("command failed: " + e.getMessage());
ChatMessage login = new ChatMessage(
MessageType.LOGIN,
username,
"",
""
);
out.writeObject(login);
new Thread(new ServerListener(in)).start();
while (true) {
try {
String text = scanner.nextLine();
if (text.startsWith("/msg ")) {
String[] parts = text.split(" ", 3);
if (parts.length < 3) {
System.out.println("Wrong command.");
continue;
} }
ChatMessage message = new ChatMessage(
MessageType.PRIVATE_MESSAGE,
username,
parts[1],
parts[2]
);
out.writeObject(message);
out.flush();
} }
else if (text.equals("/users")) {
ChatMessage message = new ChatMessage(
MessageType.USER_LIST,
username,
"",
""
);
out.writeObject(message);
out.flush();
} }
else if (text.startsWith("/sendfile ")) {
String[] parts = text.split(" ", 3);
if (parts.length < 3) {
System.out.println("Wrong command.");
continue;
}
File file = new File(parts[2]);
if (!file.exists()) {
System.out.println("File not found.");
continue;
}
byte[] data = Files.readAllBytes(file.toPath());
FileMessage fileMessage = new FileMessage(
username,
parts[1],
file.getName(),
data
);
out.writeObject(fileMessage);
out.flush();
System.out.println("File sent.");
}
else {
ChatMessage message = new ChatMessage(
MessageType.PUBLIC_MESSAGE,
username,
"",
text
);
out.writeObject(message);
out.flush();
}
} catch (Exception e) {
System.out.println("Command failed.");
}
}
} catch (Exception e) {
}
}
} }
@@ -1,15 +1,42 @@
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 UserManager userManager =
new UserManager();
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket // TODO: Create a ServerSocket
try (ServerSocket serverSocket =
new ServerSocket(5000)) {
System.out.println("Server started");
while (true) {
Socket socket =
serverSocket.accept();
ClientSession session =
new ClientSession(
socket,
userManager
);
new Thread(session).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 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.
}
} }
@@ -2,18 +2,37 @@ 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 final Socket socket;
private final UserManager userManager;
private ObjectInputStream in;
private ObjectOutputStream out;
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 {
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
@Override @Override
@@ -28,18 +47,65 @@ public class ClientSession implements Runnable {
// 5. If the username is taken, send back LOGIN_FAILED and close the socket. // 5. If the username is taken, send back LOGIN_FAILED and close the socket.
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...) // 6. Otherwise, create the user's folders with FileManager.createUserFolders(...)
// and send back LOGIN_SUCCESS. // and send back LOGIN_SUCCESS.
Object first = in.readObject();
if (!(first instanceof ChatMessage msg)
|| msg.getType() != MessageType.LOGIN) {
socket.close();
return;
}
username = msg.getSender();
if (!userManager.addUser(username, this)) {
send(new ChatMessage(
MessageType.LOGIN_FAILED,
"SERVER",
username,
"Username already exists"
));
socket.close();
return;
}
FileManager.createUserFolders(username);
send(new ChatMessage(
MessageType.LOGIN_SUCCESS,
"SERVER",
username,
"Login successful"
));
// TODO: Main message loop // TODO: Main message loop
// In a loop, call in.readObject(), you can separate messages by their type: // 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 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).
while(true){
Object obj = in.readObject();
if(obj instanceof ChatMessage mesg){
handleChatMessage(mesg);
}
else if(obj instanceof FileMessage file){
handleFileMessage(file);
}
}
} 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);
}
try {
socket.close();
} catch (IOException ignored) {
}
} }
} }
@@ -48,12 +114,27 @@ public class ClientSession implements Runnable {
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.send(msg);
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user. ClientSession target =
userManager.getUser(msg.getReceiver());
if(target != null){
target.send(msg);
}
} }
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.
send(new ChatMessage(
MessageType.USER_LIST,
"SERVER",
username,
userManager.listUsers()
));
} }
} }
} }
@@ -67,5 +148,20 @@ 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 target =
userManager.getUser(
fileMsg.getReceiver()
);
if(target != null){
target.send(fileMsg);
}
}
public synchronized void send(Object obj)
throws IOException {
out.writeObject(obj);
out.flush();
} }
} }