HW-10-last-edition
This commit is contained in:
@@ -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,19 +1,35 @@
|
|||||||
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
|
import com.university.chat.Common.MessageType;
|
||||||
// chatClient created when connecting)
|
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
|
||||||
|
public class ServerListener implements Runnable {
|
||||||
|
|
||||||
|
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
|
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
|
if (obj instanceof ChatMessage msg) {
|
||||||
// (filename + sender), it's already
|
if (msg.getType() == MessageType.USER_LIST) {
|
||||||
// saved to disk by the server.
|
System.out.println("[Online users] " + msg.getContent());
|
||||||
} catch (Exception e){
|
} else {
|
||||||
|
System.out.println(msg.getSender() + ": " + msg.getContent());
|
||||||
|
}
|
||||||
|
} else if (obj instanceof FileMessage fileMsg) {
|
||||||
|
System.out.println("[File received] '" + fileMsg.getFilename() + "' from " + fileMsg.getSender());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("Disconnected from server");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,121 @@
|
|||||||
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.FileInputStream;
|
||||||
try {
|
import java.io.ObjectInputStream;
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
import java.io.ObjectOutputStream;
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
import java.net.Socket;
|
||||||
// - "/users" -> build & send a USER_LIST request
|
import java.nio.file.Files;
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
import java.nio.file.Path;
|
||||||
// (you can use TransferProgress
|
import java.nio.file.Paths;
|
||||||
// to show progress)
|
import java.util.Scanner;
|
||||||
// and send it as a FileMessage
|
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
public class chatClient {
|
||||||
// Remember to flush() the output stream after writeObject().
|
|
||||||
} catch (Exception e){
|
private static final String SERVER_HOST = "localhost";
|
||||||
System.out.println("command failed: " + e.getMessage());
|
private static final int SERVER_PORT = 12345;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
|
||||||
|
|
||||||
|
// Output stream MUST come first on both ends to avoid handshake deadlock
|
||||||
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
out.flush();
|
||||||
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
System.out.print("Enter username: ");
|
||||||
|
String username = scanner.nextLine().trim();
|
||||||
|
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
// Wait for login response before starting the listener
|
||||||
|
Object resp = in.readObject();
|
||||||
|
if (resp instanceof ChatMessage loginResp) {
|
||||||
|
if (loginResp.getType() == MessageType.LOGIN_FAILED) {
|
||||||
|
System.out.println("Login failed: " + loginResp.getContent());
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
System.out.println(loginResp.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Listener thread handles all incoming messages from now on
|
||||||
|
Thread listener = new Thread(new ServerListener(in));
|
||||||
|
listener.setDaemon(true);
|
||||||
|
listener.start();
|
||||||
|
|
||||||
|
System.out.println("Commands: /msg <user> <text> | /users | /sendfile <user> <path> | <text>");
|
||||||
|
|
||||||
|
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> <text>");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else if (line.equals("/users")) {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, null, null));
|
||||||
|
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 targetUser = parts[1];
|
||||||
|
Path filePath = Paths.get(parts[2]);
|
||||||
|
|
||||||
|
if (!Files.exists(filePath)) {
|
||||||
|
System.out.println("File not found: " + filePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
long fileSize = Files.size(filePath);
|
||||||
|
byte[] fileData = new byte[(int) fileSize];
|
||||||
|
TransferProgress progress = new TransferProgress(fileSize);
|
||||||
|
|
||||||
|
// Read file in chunks so the progress bar actually updates
|
||||||
|
try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
|
||||||
|
int bytesRead = 0;
|
||||||
|
byte[] buffer = new byte[8192];
|
||||||
|
int chunk;
|
||||||
|
while ((chunk = fis.read(buffer)) != -1) {
|
||||||
|
System.arraycopy(buffer, 0, fileData, bytesRead, chunk);
|
||||||
|
bytesRead += chunk;
|
||||||
|
progress.update(bytesRead);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String filename = filePath.getFileName().toString();
|
||||||
|
out.writeObject(new FileMessage(username, targetUser, filename, fileData));
|
||||||
|
out.flush();
|
||||||
|
System.out.println("Sent '" + filename + "' to " + targetUser);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line));
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("command failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Failed to connect to server: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,25 @@
|
|||||||
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)
|
|
||||||
// This MUST be shared by all ClientSession threads so that
|
private static final int PORT = 12345;
|
||||||
// broadcasting and private messaging work correctly.
|
private static final UserManager userManager = new UserManager();
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
System.out.println("Chat server started on port " + PORT);
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
|
||||||
// TODO: In an infinite loop:
|
while (true) {
|
||||||
// accept an incoming client connection
|
Socket clientSocket = serverSocket.accept();
|
||||||
// make a new thread running ClientSession for each user.
|
System.out.println("New connection from " + clientSocket.getInetAddress());
|
||||||
|
Thread thread = new Thread(new ClientSession(clientSocket, userManager));
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Server error: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,70 +2,124 @@ 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 final Socket socket;
|
||||||
|
private final UserManager userManager;
|
||||||
|
private ObjectOutputStream out;
|
||||||
|
private ObjectInputStream in;
|
||||||
|
|
||||||
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 come first on both ends to avoid handshake deadlock
|
||||||
|
out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
out.flush();
|
||||||
|
in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Error setting up streams: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
|
// Login step
|
||||||
|
Object firstObj = in.readObject();
|
||||||
|
if (!(firstObj instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
username = loginMsg.getSender();
|
||||||
// 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 (!userManager.addUser(username, this)) {
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "Server", username, "Username already taken."));
|
||||||
// - if it's a ChatMessage -> call handleChatMessage(msg)
|
socket.close();
|
||||||
// - if it's a FileMessage -> call handleFileMessage(fileMsg)
|
return;
|
||||||
// Keep looping until the connection is closed (an exception will be thrown).
|
}
|
||||||
|
|
||||||
|
FileManager.createUserFolders(username);
|
||||||
|
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", username, "Welcome, " + username + "!"));
|
||||||
|
System.out.println(username + " logged in.");
|
||||||
|
|
||||||
|
// 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);
|
||||||
} finally {
|
} finally {
|
||||||
// TODO: Remove the user from UserManager so they no longer
|
if (username != null) {
|
||||||
// receive broadcasts or appear in users list
|
userManager.removeUser(username);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
socket.close();
|
||||||
|
} catch (IOException ignored) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// synchronized so concurrent broadcast calls don't interleave bytes on the stream
|
||||||
|
public synchronized void sendMessage(Object obj) throws IOException {
|
||||||
|
out.writeObject(obj);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
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()) {
|
||||||
|
try {
|
||||||
|
session.sendMessage(msg);
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to deliver to " + session.username);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case PRIVATE_MESSAGE -> {
|
case PRIVATE_MESSAGE -> {
|
||||||
// TODO: Forward this message to the receiver user.
|
ClientSession receiver = userManager.getUser(msg.getReceiver());
|
||||||
|
if (receiver != null) {
|
||||||
|
receiver.sendMessage(msg);
|
||||||
|
} else {
|
||||||
|
sendMessage(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", username,
|
||||||
|
"User '" + msg.getReceiver() + "' is not online."));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
sendMessage(new ChatMessage(MessageType.USER_LIST, "Server", username, userManager.listUsers()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 receiver = userManager.getUser(fileMsg.getReceiver());
|
||||||
|
if (receiver != null) {
|
||||||
|
receiver.sendMessage(fileMsg);
|
||||||
|
} else {
|
||||||
|
sendMessage(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", username,
|
||||||
|
"User '" + fileMsg.getReceiver() + "' is not online; file was saved locally."));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user