Complete network chat system with file sharing
This commit is contained in:
@@ -1,18 +1,54 @@
|
||||
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{
|
||||
// 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() {
|
||||
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 = in.readObject();
|
||||
if (obj instanceof ChatMessage) {
|
||||
ChatMessage msg = (ChatMessage) obj;
|
||||
switch (msg.getType()) {
|
||||
case LOGIN_SUCCESS:
|
||||
System.out.println("\n[Server] " + msg.getContent());
|
||||
break;
|
||||
case LOGIN_FAILED:
|
||||
System.out.println("\n[Server] " + msg.getContent());
|
||||
System.exit(0);
|
||||
break;
|
||||
case PUBLIC_MESSAGE:
|
||||
System.out.println("\n[" + msg.getSender() + "]: " + msg.getContent());
|
||||
break;
|
||||
case PRIVATE_MESSAGE:
|
||||
System.out.println("\n[Private from " + msg.getSender() + "]: " + msg.getContent());
|
||||
break;
|
||||
case USER_LIST:
|
||||
System.out.println("\n[Online users]: " + msg.getContent());
|
||||
break;
|
||||
default:
|
||||
System.out.println("\n[Server] " + msg.getContent());
|
||||
}
|
||||
System.out.print("> ");
|
||||
} else if (obj instanceof FileMessage) {
|
||||
FileMessage fileMsg = (FileMessage) obj;
|
||||
System.out.println("\n[File received] from " + fileMsg.getSender() +
|
||||
": " + fileMsg.getFilename() + " (saved to server_data)");
|
||||
System.out.print("> ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
|
||||
@@ -1,29 +1,112 @@
|
||||
package com.university.chat.Client;
|
||||
|
||||
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.
|
||||
import com.university.chat.Common.ChatMessage;
|
||||
import com.university.chat.Common.FileMessage;
|
||||
import com.university.chat.Common.MessageType;
|
||||
|
||||
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().
|
||||
} catch (Exception e){
|
||||
import java.io.*;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class chatClient {
|
||||
|
||||
private static ObjectOutputStream out;
|
||||
private static ObjectInputStream in;
|
||||
private static String username;
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
|
||||
Socket socket = new Socket("localhost", 12345);
|
||||
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter your username: ");
|
||||
username = scanner.nextLine().trim();
|
||||
|
||||
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, null, "");
|
||||
out.writeObject(loginMsg);
|
||||
out.flush();
|
||||
|
||||
|
||||
ServerListener listener = new ServerListener(in);
|
||||
new Thread(listener).start();
|
||||
while (true){
|
||||
try {
|
||||
System.out.print("> ");
|
||||
String line = scanner.nextLine();
|
||||
if (line == null) break;
|
||||
|
||||
if (line.equals("/exit") || line.equals("/quit")) {
|
||||
System.out.println("Disconnecting...");
|
||||
break;
|
||||
}
|
||||
|
||||
if (line.startsWith("/msg ")) {
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length < 3) {
|
||||
System.out.println("Usage: /msg <username> <message>");
|
||||
continue;
|
||||
}
|
||||
String target = parts[1];
|
||||
String content = parts[2];
|
||||
ChatMessage privateMsg = new ChatMessage(MessageType.PRIVATE_MESSAGE,
|
||||
username, target, content);
|
||||
out.writeObject(privateMsg);
|
||||
out.flush();
|
||||
} else if (line.equals("/users")) {
|
||||
ChatMessage userListReq = new ChatMessage(MessageType.USER_LIST,
|
||||
username, null, "");
|
||||
out.writeObject(userListReq);
|
||||
out.flush();
|
||||
} else if (line.startsWith("/sendfile ")) {
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length < 3) {
|
||||
System.out.println("Usage: /sendfile <username> <filepath>");
|
||||
continue;
|
||||
}
|
||||
String target = parts[1];
|
||||
String filePath = parts[2];
|
||||
|
||||
Path path = Paths.get(filePath);
|
||||
if (!Files.exists(path) || Files.isDirectory(path)) {
|
||||
System.out.println("File does not exist or is a directory.");
|
||||
continue;
|
||||
}
|
||||
|
||||
byte[] data = Files.readAllBytes(path);
|
||||
String filename = path.getFileName().toString();
|
||||
|
||||
TransferProgress progress = new TransferProgress(data.length);
|
||||
progress.update(data.length);
|
||||
|
||||
FileMessage fileMsg = new FileMessage(username, target, filename, data);
|
||||
out.writeObject(fileMsg);
|
||||
out.flush();
|
||||
System.out.println("File sent to " + target);
|
||||
} else {
|
||||
ChatMessage publicMsg = new ChatMessage(MessageType.PUBLIC_MESSAGE,
|
||||
username, null, line);
|
||||
out.writeObject(publicMsg);
|
||||
out.flush();
|
||||
}
|
||||
}catch (IOException e) {
|
||||
System.out.println("Connection lost. Exiting...");
|
||||
break;
|
||||
} catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
socket.close();
|
||||
scanner.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println("Connection error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
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
|
||||
final int PORT = 12345;
|
||||
|
||||
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
|
||||
System.out.println("Chat Server started on port " + PORT);
|
||||
|
||||
while (true) {
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
System.out.println("New client connected: " + clientSocket.getInetAddress());
|
||||
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||
new Thread(session).start();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Server error: " + e.getMessage());
|
||||
}
|
||||
|
||||
// TODO: In an infinite loop:
|
||||
// accept an incoming client connection
|
||||
// make a new thread running ClientSession for each user.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,44 +2,94 @@ 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 {
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error initializing streams: " + e.getMessage());
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (out == null || in == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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.
|
||||
Object first = in.readObject();
|
||||
if (!(first instanceof ChatMessage)) {
|
||||
socket.close();
|
||||
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).
|
||||
ChatMessage loginMsg = (ChatMessage) first;
|
||||
if (loginMsg.getType() != MessageType.LOGIN) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
String requestedUsername = loginMsg.getSender();
|
||||
|
||||
if (!userManager.addUser(requestedUsername, this)) {
|
||||
ChatMessage failure = new ChatMessage(MessageType.LOGIN_FAILED, "Server", null,
|
||||
"Username '" + requestedUsername + "' is already taken.");
|
||||
out.writeObject(failure);
|
||||
out.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
this.username = requestedUsername;
|
||||
FileManager.createUserFolders(username);
|
||||
|
||||
ChatMessage success = new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", null,
|
||||
"Welcome " + username + "!");
|
||||
out.writeObject(success);
|
||||
out.flush();
|
||||
|
||||
System.out.println("User logged in: " + username);
|
||||
|
||||
while (true) {
|
||||
Object obj = in.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
|
||||
if (username != null) {
|
||||
userManager.removeUser(username);
|
||||
}
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,14 +97,34 @@ 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.
|
||||
for (ClientSession session : userManager.getAllSessions()) {
|
||||
session.out.writeObject(msg);
|
||||
session.out.flush();
|
||||
}
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
String receiver = msg.getReceiver();
|
||||
ClientSession target = userManager.getUser(receiver);
|
||||
if (target != null) {
|
||||
target.out.writeObject(msg);
|
||||
target.out.flush();
|
||||
} else {
|
||||
ChatMessage error = new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server",
|
||||
msg.getSender(), "User '" + receiver + "' is not online.");
|
||||
out.writeObject(error);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
String list = userManager.listUsers();
|
||||
ChatMessage reply = new ChatMessage(MessageType.USER_LIST, "Server",
|
||||
msg.getSender(), list);
|
||||
out.writeObject(reply);
|
||||
out.flush();
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +136,15 @@ 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 target = userManager.getUser(fileMsg.getReceiver());
|
||||
if (target != null) {
|
||||
target.out.writeObject(fileMsg);
|
||||
target.out.flush();
|
||||
}else {
|
||||
ChatMessage error = new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server",
|
||||
fileMsg.getSender(), "User '" + fileMsg.getReceiver() + "' is not online. File saved on server.");
|
||||
out.writeObject(error);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user