2 Commits
Author SHA1 Message Date
peyman 140dfc357d Merge pull request '10' (#1) from develop into main
Reviewed-on: SoroushZiaee/HW-10-Socket-Programming#1
2026-07-23 20:21:38 +00:00
SoroushZiaee 77db61b8c2 10 2026-07-12 16:05:42 +03:30
4 changed files with 216 additions and 65 deletions
@@ -1,20 +1,45 @@
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 com.university.chat.Common.MessageType;
import java.io.ObjectInputStream;
public class ServerListener implements Runnable {
private 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){
System.out.println("Disconnected from server");
while (true) {
Object obj = in.readObject();
if (obj instanceof ChatMessage) {
ChatMessage msg = (ChatMessage) obj;
if (msg.getType() == MessageType.PUBLIC_MESSAGE) {
System.out.println("\n[Public] " + msg.getSender() + ": " + msg.getContent());
} else if (msg.getType() == MessageType.PRIVATE_MESSAGE) {
System.out.println("\n[Private from " + msg.getSender() + "]: " + msg.getContent());
} else if (msg.getType() == MessageType.USER_LIST) {
System.out.println("\n[Server]: " + msg.getContent());
} else {
System.out.println("\n[" + msg.getSender() + "]: " + msg.getContent());
}
}
else if (obj instanceof FileMessage) {
FileMessage fileMsg = (FileMessage) obj;
System.out.println("\n[File Received] Name: " + fileMsg.getFilename() + " | From: " + fileMsg.getSender() + " (Saved to server disk)");
}
}
} catch (Exception e) {
System.out.println("\nDisconnected from server.");
System.exit(0);
}
}
}
}
@@ -1,29 +1,100 @@
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.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Scanner;
public class chatClient {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
String serverIp = "localhost";
int port = 8080;
Socket socket = new Socket(serverIp, port);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
System.out.print("Enter your username: ");
String username = scanner.nextLine();
out.writeObject(new ChatMessage(MessageType.LOGIN, username, "Server", ""));
out.flush();
Object response = in.readObject();
if (response instanceof ChatMessage) {
ChatMessage loginResp = (ChatMessage) response;
if (loginResp.getType() == MessageType.LOGIN_FAILED) {
System.out.println("Login failed: " + loginResp.getContent());
socket.close();
return;
}
System.out.println("Login successful!");
}
new Thread(new ServerListener(in)).start();
System.out.println("\nCommands:");
System.out.println("/msg <user> <text> - Send private message");
System.out.println("/users - List online users");
System.out.println("/sendfile <user> <path> - Send a file");
System.out.println("<anything else> - Send public message\n");
while (true) {
String input = scanner.nextLine();
if (input.startsWith("/msg ")) {
String[] parts = input.split(" ", 3);
if (parts.length == 3) {
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]));
} else {
System.out.println("Usage: /msg <user> <text>");
}
} else if (input.equals("/users")) {
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, "Server", ""));
} else if (input.startsWith("/sendfile ")) {
String[] parts = input.split(" ", 3);
if (parts.length == 3) {
String receiver = parts[1];
File file = new File(parts[2]);
if (file.exists() && file.isFile()) {
byte[] data = Files.readAllBytes(file.toPath());
TransferProgress progress = new TransferProgress(data.length);
for(int i = 0; i <= data.length; i += data.length / 10 + 1) {
progress.update(i);
Thread.sleep(50);
}
progress.update(data.length);
out.writeObject(new FileMessage(username, receiver, file.getName(), data));
System.out.println("File sent to server!");
} else {
System.out.println("File not found!");
}
} else {
System.out.println("Usage: /sendfile <user> <filepath>");
}
} else {
if (!input.trim().isEmpty()) {
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "All", input));
}
}
out.flush();
}
} catch (Exception e) {
System.out.println("Client error or connection lost: " + e.getMessage());
}
}
}
}
@@ -1,15 +1,24 @@
package com.university.chat.Server;
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();
private static final int PORT = 8080;
public static void main(String[] args) {
// TODO: Create a ServerSocket
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is running on port " + PORT + "...");
// TODO: In an infinite loop:
// accept an incoming client connection
// make a new thread running ClientSession for each user.
while (true) {
Socket clientSocket = serverSocket.accept();
ClientSession session = new ClientSession(clientSocket, userManager);
new Thread(session).start();
}
} catch (Exception e) {
System.out.println("Server exception: " + e.getMessage());
}
}
}
}
@@ -2,70 +2,116 @@ 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 String username;
private Socket socket;
private UserManager userManager;
private ObjectOutputStream out;
private ObjectInputStream in;
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("Error initializing streams: " + e.getMessage());
}
}
@Override
public void run() {
try {
Object firstObj = in.readObject();
if (firstObj instanceof ChatMessage) {
ChatMessage loginMsg = (ChatMessage) firstObj;
// 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 (loginMsg.getType() == MessageType.LOGIN) {
this.username = loginMsg.getSender();
// 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 (userManager.addUser(this.username, this)) {
FileManager.createUserFolders(this.username);
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", this.username, "Login successful!"));
System.out.println(this.username + " connected.");
} else {
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "Server", this.username, "Username already taken."));
socket.close();
return;
}
} else {
socket.close();
return;
}
}
while (true) {
Object obj = in.readObject();
if (obj instanceof ChatMessage) {
handleChatMessage((ChatMessage) obj);
} else if (obj instanceof FileMessage) {
handleFileMessage((FileMessage) obj);
}
}
} 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 void sendMessage(Object msg) throws IOException {
out.writeObject(msg);
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()) {
if (!session.username.equals(this.username)) {
session.sendMessage(msg);
}
}
}
case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user.
ClientSession receiverSession = userManager.getUser(msg.getReceiver());
if (receiverSession != null) {
receiverSession.sendMessage(msg);
} else {
sendMessage(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", this.username, "User " + msg.getReceiver() + " is offline."));
}
}
case USER_LIST -> {
// TODO: Reply to the requester with the list of online users.
String users = userManager.listUsers();
sendMessage(new ChatMessage(MessageType.USER_LIST, "Server", this.username, "Online users: " + users));
}
}
}
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 receiverSession = userManager.getUser(fileMsg.getReceiver());
if (receiverSession != null) {
receiverSession.sendMessage(fileMsg);
}
}
}