2 Commits
Author SHA1 Message Date
Aryan b37b60942d Merge pull request 'complet' (#1) from develop into main
Reviewed-on: amirmohammad/HW-10-Socket-Programming#1

100 / 100
2026-07-05 02:24:30 +00:00
amirmohammad 8eb06bd1c2 complet 2026-06-20 11:38:54 +03:30
4 changed files with 311 additions and 66 deletions
@@ -1,19 +1,33 @@
package com.university.chat.Client; package com.university.chat.Client;
public class ServerListener implements Runnable{ import com.university.chat.Common.ChatMessage;
// TODO: store the ObjectInputStream from the user socket import com.university.chat.Common.FileMessage;
// (this should be the same input stream the
// chatClient created when connecting) import java.io.ObjectInputStream;
public class ServerListener implements Runnable {
private 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 chatMessage) {
// saved to disk by the server. System.out.println( chatMessage.getSender() + ": " + chatMessage.getContent());
} catch (Exception e){ }
else if (obj instanceof FileMessage fileMessage) {
System.out.println( "File received: " + fileMessage.getFilename() + " from " + fileMessage.getSender());
}
}
} catch (Exception e) {
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
} }
@@ -1,29 +1,111 @@
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;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class chatClient { public class chatClient {
public static void main() { 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.
while (true){
try { try {
// TODO: Program loop — read a line from the console and act on it: Socket socket = new Socket("localhost", 5000);
// - "/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("Username: ");
} catch (Exception e){ String username = scanner.nextLine();
System.out.println("command failed: " + e.getMessage());
ChatMessage loginMessage = new ChatMessage(MessageType.LOGIN, username, null, null);
out.writeObject(loginMessage);
out.flush();
Thread listener = new Thread(new ServerListener(in));
listener.start();
while (true) {
try {
String line = scanner.nextLine();
if (line.startsWith("/msg ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /msg <user> <message>");
continue;
} }
ChatMessage privateMessage = new ChatMessage( MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]);
out.writeObject(privateMessage);
out.flush();
}
else if (line.equals("/users")) {
ChatMessage userListRequest = new ChatMessage(MessageType.USER_LIST, username, null, null);
out.writeObject(userListRequest);
out.flush();
}
else if (line.startsWith("/sendfile ")) {
String[] parts = line.split(" ", 3);
if (parts.length < 3) {
System.out.println("Usage: /sendfile <user> <path>");
continue;
}
String receiver = parts[1];
String filePath = parts[2];
Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
FileMessage fileMessage = new FileMessage(username, receiver, path.getFileName().toString(), data);
out.writeObject(fileMessage);
out.flush();
System.out.println("File sent.");
}
else {
ChatMessage publicMessage = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line);
out.writeObject(publicMessage);
out.flush();
}
} catch (Exception e) {
System.out.println(
"command failed: " + e.getMessage()
);
}
}
} catch (Exception e) {
System.out.println(
"Could not connect to server: " + e.getMessage()
);
} }
} }
} }
@@ -1,15 +1,49 @@
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)
// This MUST be shared by all ClientSession threads so that private static final UserManager USER_MANAGER =
// broadcasting and private messaging work correctly. new UserManager();
private static final int PORT = 5000;
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket
// TODO: In an infinite loop: try (ServerSocket serverSocket =
// accept an incoming client connection new ServerSocket(PORT)) {
// make a new thread running ClientSession for each user.
System.out.println(
"Server started on port " + PORT
);
while (true) {
Socket clientSocket =
serverSocket.accept();
System.out.println(
"New client connected: "
+ clientSocket.getInetAddress()
);
ClientSession session = new ClientSession(clientSocket, USER_MANAGER);
Thread thread =
new Thread(session);
thread.start();
}
} catch (Exception e) {
System.out.println(
"Server error: " + e.getMessage()
);
e.printStackTrace();
}
} }
} }
@@ -2,70 +2,185 @@ 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 Socket socket;
private 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() this.socket = socket;
// and an ObjectInputStream from socket.getInputStream(). this.userManager = userManager;
try {
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
} }
@Override @Override
public void run() { public void run() {
try { try {
// TODO: Welcome the user (login step) Object obj = in.readObject();
// 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.
// TODO: Main message loop if (!(obj instanceof ChatMessage)) {
// In a loop, call in.readObject(), you can separate messages by their type: socket.close();
// - if it's a ChatMessage -> call handleChatMessage(msg) return;
// - if it's a FileMessage -> call handleFileMessage(fileMsg) }
// Keep looping until the connection is closed (an exception will be thrown).
ChatMessage loginMsg = (ChatMessage) obj;
if (loginMsg.getType() != MessageType.LOGIN) {
socket.close();
return;
}
username = loginMsg.getSender();
boolean added =
userManager.addUser(username, this);
if (!added) {
ChatMessage fail = new ChatMessage(MessageType.LOGIN_FAILED, "SERVER", username, "Username already exists");
send(fail);
socket.close();
return;
}
FileManager.createUserFolders(username);
ChatMessage success = new ChatMessage(MessageType.LOGIN_SUCCESS, "SERVER", username, "Login successful");
send(success);
while (true) {
Object message = in.readObject();
if (message instanceof ChatMessage) {
handleChatMessage(
(ChatMessage) message
);
} else if (message instanceof FileMessage) {
handleFileMessage(
(FileMessage) message
);
}
}
} 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
// receive broadcasts or appear in users list if (username != null) {
userManager.removeUser(username);
}
try {
socket.close();
} catch (IOException ignored) {
}
} }
} }
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.
for (ClientSession session :
userManager.getAllSessions()) {
session.send(msg);
} }
}
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user.
ClientSession receiver =
userManager.getUser(
msg.getReceiver()
);
if (receiver != null) {
receiver.send(msg);
} }
}
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
ChatMessage reply =
new ChatMessage(
MessageType.USER_LIST,
"SERVER",
username,
userManager.listUsers()
);
send(reply);
} }
} }
} }
private void handleFileMessage(FileMessage fileMsg) throws IOException { private void handleFileMessage(FileMessage fileMsg)
// Storing the file throws IOException {
var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename());
var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), fileMsg.getFilename()); var sentPath =
FileManager.getSentPath(
fileMsg.getSender(),
fileMsg.getFilename()
);
var recvPath =
FileManager.getReceivedPath(
fileMsg.getReceiver(),
fileMsg.getFilename()
);
Files.write(sentPath, fileMsg.getData()); Files.write(sentPath, fileMsg.getData());
Files.write(recvPath, 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.send(fileMsg);
}
}
public synchronized void send(Object obj)
throws IOException {
out.writeObject(obj);
out.flush();
} }
} }