Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
061d5a059a |
@@ -1,18 +1,32 @@
|
||||
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 inputStream;
|
||||
|
||||
public ServerListener(ObjectInputStream inputStream) {
|
||||
this.inputStream = inputStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
// TODO: In an infinite loop read objects from the server
|
||||
// - if it's a ChatMessage -> print "<sender>: <content>"
|
||||
// - 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 = inputStream.readObject();
|
||||
if (obj instanceof ChatMessage msg) {
|
||||
System.out.printf("%s: %s\n", msg.getSender(), msg.getContent());
|
||||
} else if (obj instanceof FileMessage fileMsg) {
|
||||
System.out.printf(
|
||||
"Received file '%s' from %s\n",
|
||||
fileMsg.getFilename(),
|
||||
fileMsg.getSender()
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
|
||||
@@ -1,28 +1,138 @@
|
||||
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.IOException;
|
||||
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() {
|
||||
// TODO: Connecting to the server
|
||||
// 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.
|
||||
public static void main(String[] args) {
|
||||
Socket socket;
|
||||
try {
|
||||
socket = new Socket("127.0.0.1", 555);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
ObjectOutputStream out = null;
|
||||
ObjectInputStream in = null;
|
||||
try {
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.printf("Error: %s\n",e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.printf("Error: %s\n",e.getMessage());
|
||||
}
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.println("Enter your username: ");
|
||||
String username = scanner.nextLine();
|
||||
|
||||
try {
|
||||
out.writeObject(new ChatMessage(
|
||||
MessageType.LOGIN,
|
||||
username,
|
||||
null,
|
||||
username
|
||||
));
|
||||
out.flush();
|
||||
|
||||
Object loginResponse = in.readObject();
|
||||
if (loginResponse == MessageType.LOGIN_FAILED) {
|
||||
System.out.println("Login failed: username is already taken.");
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
if (loginResponse != MessageType.LOGIN_SUCCESS) {
|
||||
System.out.println("Login failed: invalid server response.");
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
Thread listenerThread = new Thread(new ServerListener(in));
|
||||
listenerThread.start();
|
||||
}
|
||||
catch (IOException | ClassNotFoundException e) {
|
||||
System.err.printf("Error: %s\n",e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
while (true){
|
||||
try {
|
||||
// TODO: Program loop — read a line from the console and act on it:
|
||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
||||
// - "/users" -> build & send a USER_LIST request
|
||||
// - "/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
|
||||
// Remember to flush() the output stream after writeObject().
|
||||
String input = scanner.nextLine();
|
||||
if (input.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] tokens = input.split("\\s+", 3);
|
||||
|
||||
switch (tokens[0]) {
|
||||
case "/msg" ->{
|
||||
if (tokens.length < 3) {
|
||||
System.err.println("Usage: /msg <user> <text>");
|
||||
continue;
|
||||
}
|
||||
out.writeObject(new ChatMessage(
|
||||
MessageType.PRIVATE_MESSAGE,
|
||||
username,
|
||||
tokens[1],
|
||||
tokens[2]
|
||||
));
|
||||
out.flush();
|
||||
}
|
||||
case "/users" ->{
|
||||
out.writeObject(new ChatMessage(
|
||||
MessageType.USER_LIST,
|
||||
username,
|
||||
null,
|
||||
""
|
||||
));
|
||||
out.flush();
|
||||
}
|
||||
case "/sendfile" ->{
|
||||
if (tokens.length < 3) {
|
||||
System.err.println("Usage: /sendfile <user> <path>");
|
||||
continue;
|
||||
}
|
||||
|
||||
Path path = Path.of(tokens[2]);
|
||||
byte[] data = Files.readAllBytes(path);
|
||||
TransferProgress progress = new TransferProgress(data.length);
|
||||
progress.update(data.length);
|
||||
|
||||
out.writeObject(new FileMessage(
|
||||
username,
|
||||
tokens[1],
|
||||
path.getFileName().toString(),
|
||||
data
|
||||
));
|
||||
out.flush();
|
||||
}
|
||||
default -> {
|
||||
out.writeObject(new ChatMessage(
|
||||
MessageType.PUBLIC_MESSAGE,
|
||||
username,
|
||||
null,
|
||||
input
|
||||
));
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
System.err.println("command failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
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 ServerSocket serverSocket;
|
||||
public static void main(String[] args) {
|
||||
// TODO: Create a ServerSocket
|
||||
try {
|
||||
serverSocket = new ServerSocket(555);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// TODO: In an infinite loop:
|
||||
// accept an incoming client connection
|
||||
// make a new thread running ClientSession for each user.
|
||||
}
|
||||
}
|
||||
while (true){
|
||||
try {
|
||||
Socket socket = serverSocket.accept();
|
||||
System.out.println("New client accepted");
|
||||
ClientSession session = new ClientSession(socket, userManager);
|
||||
new Thread(session).start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Unable to establish connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,44 +2,89 @@ 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.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
|
||||
public class ClientSession implements Runnable {
|
||||
|
||||
private final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private String username;
|
||||
private ObjectOutputStream outputStream;
|
||||
private ObjectInputStream inputStream;
|
||||
|
||||
public ClientSession(Socket socket, UserManager userManager) {
|
||||
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
|
||||
// and an ObjectInputStream from socket.getInputStream().
|
||||
this.userManager = userManager;
|
||||
this.socket = socket;
|
||||
try {
|
||||
outputStream = new ObjectOutputStream(socket.getOutputStream());
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.printf("Error: %s\n",e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
inputStream = new ObjectInputStream(socket.getInputStream());
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.printf("Error: %s\n",e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
System.out.println("Welcome.");
|
||||
|
||||
// TODO: Welcome the user (login step)
|
||||
// 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.
|
||||
boolean isLogin = false;
|
||||
Object firstOjbect = inputStream.readObject();
|
||||
if (firstOjbect instanceof ChatMessage){
|
||||
isLogin = ((ChatMessage)firstOjbect).getType() == MessageType.LOGIN;
|
||||
}
|
||||
|
||||
// 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).
|
||||
if (!isLogin) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
username = ((ChatMessage)firstOjbect).getContent();
|
||||
if (userManager.addUser(username, this)){
|
||||
System.out.printf("Successfully registered: %s\n", username);
|
||||
FileManager.createUserFolders(username);
|
||||
outputStream.writeObject(MessageType.LOGIN_SUCCESS);
|
||||
outputStream.flush();
|
||||
}
|
||||
else {
|
||||
System.err.printf("Error: a user with username: %s already exists.\n",username);
|
||||
outputStream.writeObject(MessageType.LOGIN_FAILED);
|
||||
outputStream.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
Object obj = inputStream.readObject();
|
||||
|
||||
if (obj instanceof ChatMessage) {
|
||||
handleChatMessage((ChatMessage) obj);
|
||||
}
|
||||
else if (obj instanceof FileMessage) {
|
||||
handleFileMessage((FileMessage) obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
finally {
|
||||
|
||||
userManager.removeUser(username);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,17 +92,43 @@ public class ClientSession implements Runnable {
|
||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||
switch (msg.getType()) {
|
||||
case PUBLIC_MESSAGE -> {
|
||||
// TODO: Broadcast this message to every connected client.
|
||||
Iterable<ClientSession> users = userManager.getAllSessions();
|
||||
for (ClientSession user : users) {
|
||||
if (user != this) {
|
||||
user.sendObject(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
ClientSession receiver = userManager.getUser(msg.getReceiver());
|
||||
if (receiver != null) {
|
||||
receiver.sendObject(msg);
|
||||
}
|
||||
else {
|
||||
sendObject(new ChatMessage(
|
||||
MessageType.PRIVATE_MESSAGE,
|
||||
"server",
|
||||
username,
|
||||
"User not found: " + msg.getReceiver()
|
||||
));
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
sendObject(new ChatMessage(
|
||||
MessageType.USER_LIST,
|
||||
"server",
|
||||
username,
|
||||
userManager.listUsers()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void sendObject(Object obj) throws IOException {
|
||||
outputStream.writeObject(obj);
|
||||
outputStream.flush();
|
||||
}
|
||||
|
||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
||||
// Storing the file
|
||||
var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename());
|
||||
@@ -66,6 +137,7 @@ public class ClientSession implements Runnable {
|
||||
Files.write(sentPath, fileMsg.getData());
|
||||
Files.write(recvPath, fileMsg.getData());
|
||||
|
||||
// TODO: Forward the received file-message to the destination user.
|
||||
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
|
||||
receiver.sendObject(fileMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user