implement socket-programming chat server and client core logic

This commit is contained in:
2026-06-30 12:48:36 +03:30
parent 240eac0504
commit 392800a9e6
7 changed files with 278 additions and 68 deletions
Generated
+1
View File
@@ -0,0 +1 @@
chatClient.java
+1 -1
View File
@@ -8,7 +8,7 @@
</list> </list>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_21_PREVIEW" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>
+2 -2
View File
@@ -9,8 +9,8 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>25</maven.compiler.source> <maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target> <maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
@@ -1,20 +1,37 @@
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 {
// ذخیره ObjectInputStream دریافتی از چت‌کلاینت اصلی
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 // حلقه بی‌انتها برای خواندن مداوم آبجکت‌ها از سرور
// - if it's a ChatMessage -> print "<sender>: <content>" while (true) {
// - if it's a FileMessage -> print that a file was received Object serverData = in.readObject();
// (filename + sender), it's already
// saved to disk by the server. if (serverData instanceof ChatMessage msg) {
} catch (Exception e){ // چاپ پیام‌های متنی دریافتی (سیستمی، عمومی یا خصوصی)
System.out.println(msg.getSender() + ": " + msg.getContent());
} else if (serverData instanceof FileMessage fileMsg) {
// اعلام دریافت موفقیت‌آمیز فایل که سرور از قبل ذخیره‌اش کرده
System.out.println("[Notification] File received: '" + fileMsg.getFilename() +
"' from user '" + fileMsg.getSender() + "'. Saved on disk.");
}
}
} catch (Exception e) {
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
} }
} }
} }
@@ -1,29 +1,128 @@
package com.university.chat.Client; package com.university.chat.Client;
public class chatClient { import com.university.chat.Common.ChatMessage;
public static void main() { import com.university.chat.Common.FileMessage;
// TODO: Connecting to the server import com.university.chat.Common.MessageType;
// 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){ import java.io.BufferedReader;
try { import java.io.File;
// TODO: Program loop — read a line from the console and act on it: import java.io.InputStreamReader;
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE import java.io.ObjectInputStream;
// - "/users" -> build & send a USER_LIST request import java.io.ObjectOutputStream;
// - "/sendfile <user> <path>" -> read the file into a byte[] import java.net.Socket;
// (you can use TransferProgress import java.nio.file.Files;
// to show progress)
// and send it as a FileMessage public class chatClient {
// - anything else -> send a PUBLIC_MESSAGE private static Socket socket;
// Remember to flush() the output stream after writeObject(). private static ObjectOutputStream out;
} catch (Exception e){ private static ObjectInputStream in;
System.out.println("command failed: " + e.getMessage()); private static BufferedReader consoleReader;
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 12345;
try {
consoleReader = new BufferedReader(new InputStreamReader(System.in));
// ۱. اتصال سوکت و ایجاد تقدمی استریم‌ها
socket = new Socket(host, port);
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
System.out.print("Enter your username: ");
String username = consoleReader.readLine();
if (username == null || username.trim().isEmpty()) {
username = "Anonymous";
} }
// ارسال پکت ورود با فرمت ۴ پارامتری درست
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, "Server", username);
out.writeObject(loginMsg);
out.flush();
// شروع کار ترد شنونده بک‌گراند
ServerListener serverListener = new ServerListener(in);
Thread listenerThread = new Thread(serverListener);
listenerThread.setDaemon(true);
listenerThread.start();
System.out.println("Connected to server! Available commands:\n" +
" - /msg <user> <text>\n" +
" - /users\n" +
" - /sendfile <user> <path>\n" +
" - Or just type anything to send a public message.\n");
// ۲. حلقه برنامه برای دریافت دستورات ترمینال
while (true) {
String line = consoleReader.readLine();
if (line == null) break;
if (line.trim().isEmpty()) continue;
try {
if (line.startsWith("/msg ")) {
String[] parts = line.split(" ", 3);
if (parts.length >= 3) {
String receiver = parts[1];
String text = parts[2];
ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, receiver, text);
out.writeObject(privateMsg);
} else {
System.out.println("Usage: /msg <user> <text>");
}
} else if (line.equals("/users")) {
ChatMessage listReq = new ChatMessage(MessageType.USER_LIST, username, "Server", "");
out.writeObject(listReq);
} else if (line.startsWith("/sendfile ")) {
String[] parts = line.split(" ", 3);
if (parts.length >= 3) {
String receiver = parts[1];
String filepath = parts[2];
File file = new File(filepath);
if (file.exists() && file.isFile()) {
byte[] fileData = Files.readAllBytes(file.toPath());
FileMessage fileMsg = new FileMessage(username, receiver, file.getName(), fileData);
out.writeObject(fileMsg);
System.out.println("File sent to server for routing...");
} else {
System.out.println("File not found at path: " + filepath);
}
} else {
System.out.println("Usage: /sendfile <user> <path>");
}
} else {
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "All", line);
out.writeObject(publicMsg);
}
out.flush();
} catch (Exception e) {
System.out.println("Command failed: " + e.getMessage());
}
}
} catch (Exception e) {
System.out.println("Client error: " + e.getMessage());
} finally {
cleanup();
} }
} }
}
// متد کلین‌آپ مطابق دقیق ساختار عکسی که فرستادی برای آزادسازی پورت‌ها
private static void cleanup() {
try {
if (in != null) in.close();
} catch (Exception ignored) {}
try {
if (out != null) out.close();
} catch (Exception ignored) {}
try {
if (consoleReader != null) consoleReader.close();
} catch (Exception ignored) {}
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (Exception ignored) {}
}
}
@@ -1,15 +1,32 @@
package com.university.chat.Server; package com.university.chat.Server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer { public class ChatServer {
// TODO: declare a single shared UserManager instance (static final) // تعریف نمونه اشتراکی UserManager به صورت static final برای دسترسی تمام جلسات
// This MUST be shared by all ClientSession threads so that private static final UserManager userManager = new UserManager();
// broadcasting and private messaging work correctly. private static final int PORT = 12345;
public static void main(String[] args) { public static void main(String[] args) {
// TODO: Create a ServerSocket System.out.println("Advanced Chat Server starting...");
// ساخت ServerSocket روی پورت مشخص شده
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is running and listening on port " + PORT);
// TODO: In an infinite loop: // حلقه بی‌انتها برای پذیرش کلاینت‌های جدید
// accept an incoming client connection while (true) {
// make a new thread running ClientSession for each user. Socket clientSocket = serverSocket.accept();
System.out.println("New client connected from: " + clientSocket.getRemoteSocketAddress());
// ساخت یک ClientSession جدید و سپردن آن به یک ترد مجزا
ClientSession session = new ClientSession(clientSocket, userManager);
Thread sessionThread = new Thread(session);
sessionThread.start();
}
} catch (IOException e) {
System.err.println("Server exception: " + e.getMessage());
}
} }
} }
@@ -2,70 +2,146 @@ 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 final Socket socket;
private final UserManager userManager;
private ObjectOutputStream out;
private ObjectInputStream in;
private String username; private String username;
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 {
// ایجاد استریم خروجی قبل از ورودی جهت جلوگیری از Stream Deadlock
this.out = new ObjectOutputStream(socket.getOutputStream());
this.out.flush();
this.in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
System.err.println("Error initializing streams: " + e.getMessage());
}
} }
@Override @Override
public void run() { public void run() {
try { try {
// ۱. فرآیند لاگین کلاینت
Object firstObject = in.readObject();
if (firstObject instanceof ChatMessage msg && msg.getType() == MessageType.LOGIN) {
this.username = msg.getSender();
// TODO: Welcome the user (login step) // ثبت کاربر در UserManager فعال سرور
// 1. Read the first object sent by the client. if (!userManager.addUser(username, this)) {
// 2. Check it's a ChatMessage with type LOGIN. ChatMessage failMsg = new ChatMessage(MessageType.LOGIN_FAILED, "Server", username, "Username already taken.");
// 3. Extract the username. out.writeObject(failMsg);
// 4. Try to register the user via userManager.addUser(...). out.flush();
// 5. If the username is taken, send back LOGIN_FAILED and close the socket. socket.close();
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...) return;
// and send back LOGIN_SUCCESS. } else {
// ایجاد پوشه‌های کاربر روی دیسک سرور و تایید لاگین
FileManager.createUserFolders(username);
ChatMessage successMsg = new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", username, "Welcome to the chat!");
out.writeObject(successMsg);
out.flush();
System.out.println("User " + username + " successfully logged in.");
// TODO: Main message loop // اطلاع‌رسانی به دیگران
// In a loop, call in.readObject(), you can separate messages by their type: broadcastSystemMessage("[System] " + username + " joined the chat.");
// - if it's a ChatMessage -> call handleChatMessage(msg) }
// - if it's a FileMessage -> call handleFileMessage(fileMsg) } else {
// Keep looping until the connection is closed (an exception will be thrown). socket.close();
return;
}
// ۲. حلقه اصلی دریافت پکت‌ها
while (true) {
Object received = in.readObject();
if (received instanceof ChatMessage chatMsg) {
handleChatMessage(chatMsg);
} else if (received instanceof FileMessage fileMsg) {
handleFileMessage(fileMsg);
}
}
} 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);
broadcastSystemMessage("[System] " + username + " left the chat.");
}
try {
if (!socket.isClosed()) 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.sendObject(msg);
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user. // پیدا کردن سشن گیرنده خصوصی و ارسال پکت
ClientSession targetSession = userManager.getUser(msg.getReceiver());
if (targetSession != null) {
targetSession.sendObject(msg);
} else {
// اگر کاربر آنلاین نبود، پیغام خطا به فرستنده برمی‌گردد
sendObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", username, "User " + msg.getReceiver() + " is offline."));
}
} }
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users. // دریافت لیست متنی با متد تایید شده listUsers()
String onlineUsers = userManager.listUsers();
ChatMessage listReply = new ChatMessage(MessageType.USER_LIST, "Server", username, "Online users: " + onlineUsers);
sendObject(listReply);
} }
} }
} }
private void handleFileMessage(FileMessage fileMsg) throws IOException { private void handleFileMessage(FileMessage fileMsg) throws IOException {
// Storing the file
var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename()); var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename());
var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), 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 targetSession = userManager.getUser(fileMsg.getReceiver());
if (targetSession != null) {
targetSession.sendObject(fileMsg);
}
}
// متد ترد-ایمن برای فرستادن آبجکت روی شبکه
public synchronized void sendObject(Object obj) throws IOException {
if (out != null) {
out.writeObject(obj);
out.flush();
}
}
// متد کمکی برودکست پیام‌های سیستمی ورود و خروج
private void broadcastSystemMessage(String content) {
ChatMessage sysMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "All", content);
for (ClientSession session : userManager.getAllSessions()) {
try {
session.sendObject(sysMsg);
} catch (IOException ignored) {}
}
} }
} }