Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f90474f375 | ||
|
|
55cd540fa0 |
@@ -1,9 +1,19 @@
|
||||
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 +23,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 obj = in.readObject();
|
||||
if (obj instanceof ChatMessage msg) {
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
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;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class chatClient {
|
||||
public static void main() {
|
||||
public static void main(String[] args) {
|
||||
// TODO: Connecting to the server
|
||||
// 1. Create a socket and connect to the server
|
||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
||||
@@ -9,6 +20,38 @@ public class chatClient {
|
||||
// 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.
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
String username;
|
||||
ObjectOutputStream out;
|
||||
ObjectInputStream in;
|
||||
|
||||
try {
|
||||
Socket socket = new Socket("localhost", 12345);
|
||||
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
|
||||
System.out.print("Enter your username: ");
|
||||
username = scanner.nextLine().trim();
|
||||
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
|
||||
out.flush();
|
||||
|
||||
Object response = in.readObject();
|
||||
if (response instanceof ChatMessage loginReply) {
|
||||
System.out.println(loginReply.getContent());
|
||||
if (loginReply.getType() == MessageType.LOGIN_FAILED) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
new Thread(new ServerListener(in)).start();
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Could not connect to server: " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
while (true){
|
||||
try {
|
||||
@@ -21,9 +64,51 @@ public class chatClient {
|
||||
// and send it as a FileMessage
|
||||
// - anything else -> send a PUBLIC_MESSAGE
|
||||
// Remember to flush() the output stream after writeObject().
|
||||
String line = scanner.nextLine();
|
||||
|
||||
if (line.startsWith("/msg ")) {
|
||||
String[] parts = line.substring(5).split(" ", 2);
|
||||
if (parts.length < 2) {
|
||||
System.out.println("Usage: /msg <username> <message>");
|
||||
continue;
|
||||
}
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[0], parts[1]));
|
||||
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.substring(10).split(" ", 2);
|
||||
if (parts.length < 2) {
|
||||
System.out.println("Usage: /sendfile <username> <filepath>");
|
||||
continue;
|
||||
}
|
||||
String receiver = parts[0];
|
||||
Path path = Path.of(parts[1]);
|
||||
|
||||
if (!Files.exists(path)) {
|
||||
System.out.println("File not found: " + parts[1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
byte[] data = Files.readAllBytes(path);
|
||||
String filename = path.getFileName().toString();
|
||||
|
||||
TransferProgress progress = new TransferProgress(data.length);
|
||||
progress.update(data.length);
|
||||
|
||||
out.writeObject(new FileMessage(username, receiver, filename, data));
|
||||
out.flush();
|
||||
|
||||
} else {
|
||||
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line));
|
||||
out.flush();
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,29 @@
|
||||
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.
|
||||
private static final UserManager userManager = new UserManager();
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO: Create a ServerSocket
|
||||
try (ServerSocket serverSocket = new ServerSocket(12345)) {
|
||||
|
||||
// TODO: In an infinite loop:
|
||||
// accept an incoming client connection
|
||||
// make a new thread running ClientSession for each user.
|
||||
// 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 (IOException e) {
|
||||
System.out.println("Server error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,34 @@ 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 final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private ObjectOutputStream out;
|
||||
private ObjectInputStream in;
|
||||
|
||||
private String username;
|
||||
|
||||
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("Failed to open streams: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -28,32 +44,81 @@ public class ClientSession implements Runnable {
|
||||
// 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.
|
||||
Object first = in.readObject();
|
||||
if (!(first instanceof ChatMessage loginMsg) || loginMsg.getType() != MessageType.LOGIN) {
|
||||
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "server", null, "Expected LOGIN message"));
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
username = loginMsg.getSender();
|
||||
|
||||
if (!userManager.addUser(username, this)) {
|
||||
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "server", username, "Username already taken"));
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
FileManager.createUserFolders(username);
|
||||
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "server", username, "Welcome, " + username + "!"));
|
||||
|
||||
// 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 obj = in.readObject();
|
||||
if (obj instanceof ChatMessage msg) {
|
||||
handleChatMessage(msg);
|
||||
} else if (obj 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);
|
||||
}
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void sendMessage(Object obj) throws IOException {
|
||||
out.writeObject(obj);
|
||||
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()) {
|
||||
session.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
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.PRIVATE_MESSAGE, "server", username,
|
||||
"User '" + msg.getReceiver() + "' is not online."));
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
sendMessage(new ChatMessage(MessageType.USER_LIST, "server", username, userManager.listUsers()));
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,5 +132,9 @@ public class ClientSession implements Runnable {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user