forked from AdvancedProgramming1404/HW-10-Socket-Programming
Completed Network File-Sharing Chat System backend and client logic
This commit is contained in:
Generated
+1
-1
@@ -8,7 +8,7 @@
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK">
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="loom-ea-25" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,9 +1,16 @@
|
||||
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{
|
||||
// TODO: store the ObjectInputStream from the user socket
|
||||
// (this should be the same input stream the
|
||||
// chatClient created when connecting)
|
||||
private final ObjectInputStream in;
|
||||
public ServerListener(ObjectInputStream in){
|
||||
this.in = in;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -13,6 +20,14 @@ public class ServerListener implements Runnable{
|
||||
// - if it's a FileMessage -> print that a file was received
|
||||
// (filename + sender), it's already
|
||||
// saved to disk by the server.
|
||||
while (true) {
|
||||
Object received = in.readObject();
|
||||
if (received instanceof ChatMessage chatMsg){
|
||||
System.out.println("\n" + chatMsg.getSender() + ": " + chatMsg.getContent());
|
||||
}
|
||||
else if (received instanceof FileMessage fileMsg){
|
||||
System.out.println("\n[FILE RECEIVED] '" + fileMsg.getFilename() + "' sent by " + fileMsg.getSender() + ". Saved at server.");
|
||||
}}
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
|
||||
@@ -1,29 +1,126 @@
|
||||
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.*;
|
||||
import java.net.Socket;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class chatClient {
|
||||
public static void main() {
|
||||
private static final String DEFAULT_HOST = "localhost";
|
||||
private static final int DEFAULT_PORT = 8585;
|
||||
public static void main(String[] args) {
|
||||
// TODO: Connecting to the server
|
||||
// 1. Create a socket and connect to the server
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter username: ");
|
||||
String username = scanner.nextLine().trim();
|
||||
try {
|
||||
Socket socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
|
||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
||||
// from the socket's streams — output FIRST, then input.
|
||||
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||
out.flush();
|
||||
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||
// 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.
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN, username, "SERVER", ""));
|
||||
out.flush();
|
||||
Object response = in.readObject();
|
||||
if (response instanceof ChatMessage serverMsg){
|
||||
if (serverMsg.getType() == MessageType.LOGIN_FAILED){
|
||||
System.out.println("Login failed: " + serverMsg.getContent());
|
||||
socket.close();
|
||||
scanner.close();
|
||||
return;
|
||||
}
|
||||
else if (serverMsg.getType() == MessageType.LOGIN_SUCCESS){
|
||||
System.out.println("Login successful! " + serverMsg.getContent());
|
||||
System.out.println("Commands: /msg <user> <text>, /users, /sendfile <user> <path>, or just type text for public chat.");
|
||||
}
|
||||
}
|
||||
// 3. Start a new Thread running a ServerListener(in) so incoming
|
||||
// messages are handled concurrently.
|
||||
ServerListener listener = new ServerListener(in);
|
||||
Thread listenerThread = new Thread(listener);
|
||||
listenerThread.start();
|
||||
|
||||
while (true){
|
||||
try {
|
||||
// TODO: Program loop — read a line from the console and act on it:
|
||||
String line = scanner.nextLine().trim();
|
||||
if (line.isEmpty()) continue;
|
||||
if (line.startsWith("/msg ")){
|
||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length >= 3){
|
||||
String targetUser = parts[1];
|
||||
String text = parts[2];
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, targetUser, text));
|
||||
out.flush();
|
||||
}
|
||||
else{
|
||||
System.out.println("Usage: /msg <user> <text>");
|
||||
}
|
||||
}
|
||||
else if (line.equals("/users")){
|
||||
// - "/users" -> build & send a USER_LIST request
|
||||
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, "SERVER", ""));
|
||||
out.flush();
|
||||
}
|
||||
else if (line.startsWith("/sendfile ")){
|
||||
// - "/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
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length >= 3){
|
||||
String targetUser = parts[1];
|
||||
String filePath = parts[2];
|
||||
File file = new File(filePath);
|
||||
if (!file.exists() || !file.isFile()){
|
||||
System.out.println("File does not exist or is not a valid file.");
|
||||
continue;
|
||||
}
|
||||
|
||||
long fileSize = file.length();
|
||||
byte[] fileData = new byte[(int) fileSize];
|
||||
// Reading file while simulating the TransferProgress bar
|
||||
try (FileInputStream fis = new FileInputStream(file)){
|
||||
TransferProgress progress = new TransferProgress(fileSize);
|
||||
int bytesRead;
|
||||
int totalBytesRead = 0;
|
||||
byte[] buffer = new byte[4096];
|
||||
|
||||
while ((bytesRead = fis.read(buffer)) != -1){
|
||||
System.arraycopy(buffer, 0, fileData, totalBytesRead, bytesRead);
|
||||
totalBytesRead += bytesRead;
|
||||
progress.update(totalBytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
FileMessage fileMsg = new FileMessage(username, targetUser, file.getName(), fileData);
|
||||
out.writeObject(fileMsg);
|
||||
out.flush();
|
||||
System.out.println("File sent to server successfully.");
|
||||
}
|
||||
else{
|
||||
System.out.println("Usage: /sendfile <user> <path>");
|
||||
}
|
||||
}
|
||||
else{
|
||||
// - anything else -> send a PUBLIC_MESSAGE
|
||||
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "ALL", line));
|
||||
out.flush();
|
||||
}
|
||||
// Remember to flush() the output stream after writeObject().
|
||||
} catch (Exception e){
|
||||
}
|
||||
catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e){
|
||||
System.out.println("Client Error: " + e.getMessage());
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
package com.university.chat.Server;
|
||||
import java.io.IOException;
|
||||
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 = 8585;
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO: Create a ServerSocket
|
||||
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
|
||||
System.out.println("Chat Server started 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();
|
||||
System.out.println("New client connecting: " + clientSocket.getRemoteSocketAddress());
|
||||
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||
Thread sessionThread = new Thread(session);
|
||||
sessionThread.start();
|
||||
}
|
||||
}
|
||||
catch (IOException ex){
|
||||
System.err.println("Server exception: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,44 +2,96 @@ 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.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.net.Socket;
|
||||
|
||||
public class ClientSession implements Runnable {
|
||||
|
||||
private String username;
|
||||
private final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private ObjectOutputStream out;
|
||||
private ObjectInputStream in;
|
||||
|
||||
public ClientSession(Socket socket, UserManager userManager) {
|
||||
this.socket = socket;
|
||||
this.userManager = userManager;
|
||||
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
|
||||
// and an ObjectInputStream from socket.getInputStream().
|
||||
}
|
||||
try {// Output FIRST, then Input to avoid handshake deadlock
|
||||
this.out = new ObjectOutputStream(socket.getOutputStream());
|
||||
this.out.flush();
|
||||
this.in = new ObjectInputStream(socket.getInputStream());
|
||||
}
|
||||
catch (IOException ex){
|
||||
System.err.println("Error setting up streams for session: " + ex.getMessage());
|
||||
closeResources();
|
||||
} }
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (in == null || out == null) return;
|
||||
try {
|
||||
|
||||
// TODO: Welcome the user (login step)
|
||||
// 1. Read the first object sent by the client.
|
||||
Object firstObject = in.readObject();
|
||||
// 2. Check it's a ChatMessage with type LOGIN.
|
||||
// 3. Extract the username.
|
||||
if (firstObject instanceof ChatMessage msg && msg.getType() == MessageType.LOGIN) {
|
||||
this.username = msg.getSender();
|
||||
// 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 (username != null && !username.trim().isEmpty() && userManager.addUser(username, this)){
|
||||
FileManager.createUserFolders(username);
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "SERVER", username, "Welcome " + username));
|
||||
out.flush();
|
||||
System.out.println("User logged in successfully: " + username);
|
||||
}
|
||||
else{
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "SERVER", "", "Username already taken or invalid."));
|
||||
out.flush();
|
||||
closeResources();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else{
|
||||
closeResources();
|
||||
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).
|
||||
while (true){
|
||||
Object received = in.readObject();
|
||||
if (received instanceof ChatMessage chatMsg){
|
||||
handleChatMessage(chatMsg);
|
||||
}
|
||||
else if (received 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
|
||||
if (username != null){
|
||||
userManager.removeUser(username);
|
||||
}
|
||||
closeResources();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,12 +100,25 @@ public class ClientSession implements Runnable {
|
||||
switch (msg.getType()) {
|
||||
case PUBLIC_MESSAGE -> {
|
||||
// TODO: Broadcast this message to every connected client.
|
||||
for (ClientSession session : userManager.getAllSessions()) {
|
||||
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{
|
||||
//Inform sender that the receiver is offline
|
||||
sendMessage(new ChatMessage(MessageType.PUBLIC_MESSAGE, "SERVER", username, "User " + msg.getReceiver() + " is offline."));
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
String activeUsers = userManager.listUsers();
|
||||
sendMessage(new ChatMessage(MessageType.USER_LIST, "SERVER", username, activeUsers));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,5 +132,32 @@ public class ClientSession implements Runnable {
|
||||
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.sendFileMessage(fileMsg);
|
||||
}
|
||||
}
|
||||
|
||||
//to send a regular text message securely
|
||||
public synchronized void sendMessage(ChatMessage msg) throws IOException {
|
||||
out.writeObject(msg);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
//to send a file message securely
|
||||
public synchronized void sendFileMessage(FileMessage fileMsg) throws IOException {
|
||||
out.writeObject(fileMsg);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
private void closeResources() {
|
||||
try {
|
||||
if (socket != null && !socket.isClosed()){
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
catch (IOException ex){
|
||||
System.err.println("Error closing socket: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user