Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f9ecf955bf |
@@ -1,20 +1,40 @@
|
|||||||
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;
|
||||||
|
|
||||||
public class ServerListener implements Runnable{
|
public class ServerListener implements Runnable{
|
||||||
// TODO: store the ObjectInputStream from the user socket
|
private final ObjectInputStream in;
|
||||||
// (this should be the same input stream the
|
|
||||||
// chatClient created when connecting)
|
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.
|
if (msg.getType() == MessageType.USER_LIST) {
|
||||||
|
System.out.println("\n[Online Users]: " + msg.getContent());
|
||||||
|
} else if (msg.getType() == MessageType.PRIVATE_MESSAGE) {
|
||||||
|
System.out.println("\n[Private] " + msg.getSender() + ": " + msg.getContent());
|
||||||
|
} else {
|
||||||
|
System.out.println("\n" + msg.getSender() + ": " + msg.getContent());
|
||||||
|
}
|
||||||
|
} else if (obj instanceof FileMessage fileMsg) {
|
||||||
|
System.out.println("\n[File Received] Filename: '" + fileMsg.getFilename() +
|
||||||
|
"' sent by " + fileMsg.getSender() + ". It is saved on the server disk.");
|
||||||
|
}
|
||||||
|
System.out.print("> "); // Keep a prompt symbol for console usability
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("\nDisconnected from server.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,28 +1,154 @@
|
|||||||
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.FileInputStream;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
public class chatClient {
|
public class chatClient {
|
||||||
public static void main() {
|
private static final String SERVER_HOST = "localhost";
|
||||||
// TODO: Connecting to the server
|
private static final int SERVER_PORT = 12345;
|
||||||
// 1. Create a socket and connect to the server
|
|
||||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
public static void main(String[] args) {
|
||||||
// from the socket's streams — output FIRST, then input.
|
Scanner scanner = new Scanner(System.in);
|
||||||
// 2. Get the username, and send a LOGIN ChatMessage with that username
|
Socket socket = null;
|
||||||
// 3. Start a new Thread running a ServerListener(in) so incoming
|
ObjectOutputStream out = null;
|
||||||
// messages are handled concurrently.
|
ObjectInputStream in = null;
|
||||||
|
String username = "";
|
||||||
|
|
||||||
|
try {
|
||||||
|
System.out.print("Enter your username: ");
|
||||||
|
username = scanner.nextLine().trim();
|
||||||
|
|
||||||
|
if (username.isEmpty()) {
|
||||||
|
System.out.println("Username cannot be blank. Exiting...");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Create socket connection
|
||||||
|
socket = new Socket(SERVER_HOST, SERVER_PORT);
|
||||||
|
|
||||||
|
// 2. Setup Object streams — Output stream FIRST to avoid deadlocking handshake
|
||||||
|
out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
out.flush();
|
||||||
|
in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
|
||||||
|
// 3. Authenticate with LOGIN message
|
||||||
|
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, "Server", "");
|
||||||
|
out.writeObject(loginMsg);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
// Wait for Server to validate
|
||||||
|
Object response = in.readObject();
|
||||||
|
if (response instanceof ChatMessage reply) {
|
||||||
|
if (reply.getType() == MessageType.LOGIN_FAILED) {
|
||||||
|
System.out.println("Login Failed: " + reply.getContent());
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
} else if (reply.getType() == MessageType.LOGIN_SUCCESS) {
|
||||||
|
System.out.println("System: Connected successfully! " + reply.getContent());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Start listening thread for concurrent receipt
|
||||||
|
Thread listenerThread = new Thread(new ServerListener(in));
|
||||||
|
listenerThread.setDaemon(true);
|
||||||
|
listenerThread.start();
|
||||||
|
|
||||||
|
// 5. Main loop for typing interactive user input
|
||||||
|
System.out.println("Use standard messages to chat. Commands:\n/msg <user> <message>\n/users\n/sendfile <user> <filepath>\n");
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
String input = scanner.nextLine();
|
||||||
|
if (input.equalsIgnoreCase("/exit")) {
|
||||||
|
System.out.println("Exiting chat...");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.trim().isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
if (input.startsWith("/msg ")) {
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
// Pattern: /msg <username> <message>
|
||||||
// - "/users" -> build & send a USER_LIST request
|
String[] parts = input.substring(5).split(" ", 2);
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
if (parts.length < 2) {
|
||||||
// (you can use TransferProgress
|
System.out.println("Usage: /msg <username> <message>");
|
||||||
// to show progress)
|
continue;
|
||||||
// and send it as a FileMessage
|
}
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
String recipient = parts[0];
|
||||||
// Remember to flush() the output stream after writeObject().
|
String text = parts[1];
|
||||||
|
ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, recipient, text);
|
||||||
|
out.writeObject(privateMsg);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else if (input.equalsIgnoreCase("/users")) {
|
||||||
|
ChatMessage listRequest = new ChatMessage(MessageType.USER_LIST, username, "Server", "");
|
||||||
|
out.writeObject(listRequest);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else if (input.startsWith("/sendfile ")) {
|
||||||
|
// Pattern: /sendfile <username> <filepath>
|
||||||
|
String[] parts = input.substring(10).split(" ", 2);
|
||||||
|
if (parts.length < 2) {
|
||||||
|
System.out.println("Usage: /sendfile <username> <filepath>");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String recipient = parts[0];
|
||||||
|
String filepath = parts[1];
|
||||||
|
|
||||||
|
File file = new File(filepath);
|
||||||
|
if (!file.exists() || !file.isFile()) {
|
||||||
|
System.out.println("Error: File " + filepath + " does not exist.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load and read the file with a visual progress bar
|
||||||
|
byte[] fileBytes = new byte[(int) file.length()];
|
||||||
|
try (FileInputStream fis = new FileInputStream(file)) {
|
||||||
|
TransferProgress progress = new TransferProgress(file.length());
|
||||||
|
int bytesRead;
|
||||||
|
int totalRead = 0;
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
|
||||||
|
while ((bytesRead = fis.read(buffer)) != -1) {
|
||||||
|
System.arraycopy(buffer, 0, fileBytes, totalRead, bytesRead);
|
||||||
|
totalRead += bytesRead;
|
||||||
|
progress.update(totalRead);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FileMessage fileMsg = new FileMessage(username, recipient, file.getName(), fileBytes);
|
||||||
|
out.writeObject(fileMsg);
|
||||||
|
out.flush();
|
||||||
|
System.out.println("File sent successfully!");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Treat as plain text PUBLIC message
|
||||||
|
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, "All", input);
|
||||||
|
out.writeObject(publicMsg);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("command failed: " + e.getMessage());
|
System.out.println("Command failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Fatal connection exception: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
scanner.close();
|
||||||
|
try {
|
||||||
|
if (socket != null && !socket.isClosed()) socket.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Ignore silent close exceptions
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,34 @@
|
|||||||
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)
|
private static final UserManager userManager = new UserManager();
|
||||||
// This MUST be shared by all ClientSession threads so that
|
private static final int PORT = 12345; // Default port
|
||||||
// broadcasting and private messaging work correctly.
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
System.out.println("Starting Chat Server on port " + PORT + "...");
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
|
||||||
|
System.out.println("Server started successfully. Waiting for clients...");
|
||||||
|
|
||||||
// TODO: In an infinite loop:
|
while (true) {
|
||||||
// accept an incoming client connection
|
try {
|
||||||
// make a new thread running ClientSession for each user.
|
|
||||||
|
Socket clientSocket = serverSocket.accept();
|
||||||
|
System.out.println("New client connection from: " + clientSocket.getRemoteSocketAddress());
|
||||||
|
|
||||||
|
// Create a new ClientSession task and run it in its own thread
|
||||||
|
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||||
|
Thread clientThread = new Thread(session);
|
||||||
|
clientThread.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error accepting client connection: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Could not listen on port " + PORT + ": " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,70 +2,164 @@ 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 {
|
||||||
|
// Output stream MUST be created first to prevent 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 for client: " + e.getMessage());
|
||||||
|
closeResources();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
|
if (in == null || out == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 1. Welcome the user (login step)
|
||||||
|
Object firstObj = in.readObject();
|
||||||
|
if (!(firstObj instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
|
||||||
|
sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", "", "Invalid connection sequence."));
|
||||||
|
closeResources();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
this.username = loginMsg.getSender();
|
||||||
// 1. Read the first object sent by the client.
|
if (this.username == null || this.username.trim().isEmpty()) {
|
||||||
// 2. Check it's a ChatMessage with type LOGIN.
|
sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", "", "Username cannot be empty."));
|
||||||
// 3. Extract the username.
|
closeResources();
|
||||||
// 4. Try to register the user via userManager.addUser(...).
|
return;
|
||||||
// 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
|
// 2. Register user
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
if (!userManager.addUser(this.username, this)) {
|
||||||
// - if it's a ChatMessage -> call handleChatMessage(msg)
|
sendDirect(new ChatMessage(MessageType.LOGIN_FAILED, "Server", this.username, "Username already taken."));
|
||||||
// - if it's a FileMessage -> call handleFileMessage(fileMsg)
|
closeResources();
|
||||||
// Keep looping until the connection is closed (an exception will be thrown).
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Setup workspace & approve login
|
||||||
|
FileManager.createUserFolders(this.username);
|
||||||
|
sendDirect(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", this.username, "Welcome to the chat!"));
|
||||||
|
System.out.println("User online: " + this.username);
|
||||||
|
|
||||||
|
//
|
||||||
|
broadcast(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "All", this.username + " has joined the chat."));
|
||||||
|
|
||||||
|
// 4. Main message loop
|
||||||
|
while (true) {
|
||||||
|
Object obj = in.readObject();
|
||||||
|
if (obj instanceof ChatMessage msg) {
|
||||||
|
handleChatMessage(msg);
|
||||||
|
} else if (obj instanceof FileMessage fileMsg) {
|
||||||
|
handleFileMessage(fileMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected: " + username);
|
System.out.println("Disconnected: " + (username != null ? username : "Unknown client"));
|
||||||
} finally {
|
} finally {
|
||||||
// TODO: Remove the user from UserManager so they no longer
|
cleanup();
|
||||||
// receive broadcasts or appear in users list
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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 -> broadcast(msg);
|
||||||
// TODO: Broadcast this message to every connected client.
|
|
||||||
}
|
|
||||||
case PRIVATE_MESSAGE -> {
|
case PRIVATE_MESSAGE -> {
|
||||||
// TODO: Forward this message to the receiver user.
|
ClientSession recipient = userManager.getUser(msg.getReceiver());
|
||||||
|
if (recipient != null) {
|
||||||
|
recipient.sendDirect(msg);
|
||||||
|
} else {
|
||||||
|
sendDirect(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", this.username, "User " + msg.getReceiver() + " is offline."));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
String users = userManager.listUsers();
|
||||||
|
sendDirect(new ChatMessage(MessageType.USER_LIST, "Server", this.username, users));
|
||||||
}
|
}
|
||||||
|
default -> {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
||||||
// Storing the file
|
// Storing the file on the server side
|
||||||
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.
|
// Forward the received file-message to the destination user.
|
||||||
|
ClientSession recipient = userManager.getUser(fileMsg.getReceiver());
|
||||||
|
if (recipient != null) {
|
||||||
|
recipient.sendDirect(fileMsg);
|
||||||
|
} else {
|
||||||
|
sendDirect(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", this.username, "Could not deliver file. User " + fileMsg.getReceiver() + " is offline."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to send directly to this session's socket
|
||||||
|
public synchronized void sendDirect(Object obj) {
|
||||||
|
try {
|
||||||
|
out.writeObject(obj);
|
||||||
|
out.flush();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error sending message to " + username + ": " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Broadcasts to all users except sender
|
||||||
|
private void broadcast(ChatMessage msg) {
|
||||||
|
for (ClientSession session : userManager.getAllSessions()) {
|
||||||
|
if (!session.getUsername().equals(this.username)) {
|
||||||
|
session.sendDirect(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cleanup() {
|
||||||
|
if (username != null) {
|
||||||
|
userManager.removeUser(username);
|
||||||
|
broadcast(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "All", username + " has left the chat."));
|
||||||
|
}
|
||||||
|
closeResources();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeResources() {
|
||||||
|
try {
|
||||||
|
if (in != null) in.close();
|
||||||
|
if (out != null) out.close();
|
||||||
|
if (socket != null && !socket.isClosed()) socket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error closing resources: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user