Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91d28dde3c | ||
|
|
0f0d2a88e0 | ||
|
|
e7fa0c9d2c |
@@ -1,18 +1,66 @@
|
||||
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
|
||||
// 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
|
||||
// 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;
|
||||
String sender = msg.getSender();
|
||||
String content = msg.getContent();
|
||||
switch (msg.getType())
|
||||
{
|
||||
case PUBLIC_MESSAGE -> {
|
||||
System.out.println("[Public] "+sender+": "+content);
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
if ("Server".equals(sender))
|
||||
{
|
||||
System.out.println("[Server] "+content);
|
||||
} else
|
||||
{
|
||||
System.out.println("[Private] "+sender+": "+content);
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
System.out.println("Online users: "+content);
|
||||
}
|
||||
case LOGIN_SUCCESS -> {
|
||||
System.out.println("[Server] "+content);
|
||||
}
|
||||
default -> {
|
||||
System.out.println(sender+": "+content);
|
||||
}
|
||||
}
|
||||
} else if (obj instanceof FileMessage)
|
||||
{
|
||||
FileMessage file = (FileMessage) obj;
|
||||
System.out.println("Received file "+file.getFilename()+" from "+ file.getSender());
|
||||
}
|
||||
}
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
|
||||
@@ -1,18 +1,81 @@
|
||||
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.nio.file.Paths;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class chatClient {
|
||||
public static void main() {
|
||||
// TODO: Connecting to the server
|
||||
// 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.
|
||||
// 3. Start a new Thread running a ServerListener(in) so incoming messages are handled concurrently.
|
||||
|
||||
while (true){
|
||||
Socket socket = null;
|
||||
ObjectOutputStream out = null;
|
||||
ObjectInputStream in = null;
|
||||
Scanner scanner = null;
|
||||
String username = null;
|
||||
|
||||
try
|
||||
{
|
||||
socket = new Socket("localhost", 12345);
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
out.flush();
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
scanner = new Scanner(System.in);
|
||||
|
||||
System.out.println("Enter your username: ");
|
||||
username = scanner.nextLine().trim();
|
||||
if (username.isEmpty())
|
||||
{
|
||||
System.out.println("Username cannot be empty!");
|
||||
return;
|
||||
}
|
||||
|
||||
ChatMessage loginMsg = new ChatMessage(MessageType.LOGIN, username, null, username);
|
||||
out.writeObject(loginMsg);
|
||||
out.flush();
|
||||
|
||||
Object response = in.readObject();
|
||||
if (response instanceof ChatMessage)
|
||||
{
|
||||
ChatMessage loginRespose = (ChatMessage) response;
|
||||
if (loginRespose.getType() == MessageType.LOGIN_FAILED)
|
||||
{
|
||||
System.out.println("Login failed: "+loginRespose.getContent());
|
||||
return;
|
||||
} else if (loginRespose.getType() == MessageType.LOGIN_SUCCESS)
|
||||
{
|
||||
System.out.println("Login successful: "+loginRespose.getContent());
|
||||
}
|
||||
}
|
||||
|
||||
ServerListener serverListener = new ServerListener(in);
|
||||
Thread listener = new Thread(serverListener);
|
||||
listener.setDaemon(true);
|
||||
listener.start();
|
||||
|
||||
} catch (Exception e)
|
||||
{
|
||||
System.out.println(e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
boolean running = true;
|
||||
while (running){
|
||||
try {
|
||||
// TODO: Program loop — read a line from the console and act on it:
|
||||
// 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[]
|
||||
@@ -21,9 +84,81 @@ public class chatClient {
|
||||
// and send it as a FileMessage
|
||||
// - anything else -> send a PUBLIC_MESSAGE
|
||||
// Remember to flush() the output stream after writeObject().
|
||||
|
||||
System.out.println("> ");
|
||||
String line = scanner.nextLine();
|
||||
if (line == null) continue;
|
||||
line = line.trim();
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
if (line.equals("/exit")) {
|
||||
System.out.println("Goodbye!");
|
||||
running = false;
|
||||
break;
|
||||
}
|
||||
if (line.startsWith("/msg"))
|
||||
{
|
||||
String[] parts = line.split(" ", 3);
|
||||
if (parts.length < 3)
|
||||
{
|
||||
System.out.println("Usage: /msg <username> <message>");
|
||||
continue;
|
||||
}
|
||||
|
||||
String receiver = parts[1];
|
||||
String content = parts[2];
|
||||
ChatMessage msg = new ChatMessage(MessageType.PRIVATE_MESSAGE, username, receiver, content);
|
||||
out.writeObject(msg);
|
||||
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 receiver = parts[1];
|
||||
String filepath =parts[2];
|
||||
Path path = Paths.get(filepath);
|
||||
if(!Files.exists(path) || Files.isDirectory(path))
|
||||
{
|
||||
System.out.println("File not found or is a directory.");
|
||||
continue;
|
||||
}
|
||||
byte[] data = Files.readAllBytes(path);
|
||||
String filename = path.getFileName().toString();
|
||||
FileMessage fileMsg = new FileMessage(username, receiver, filename, data);
|
||||
out.writeObject(fileMsg);
|
||||
out.flush();
|
||||
System.out.println("File sent: "+filename+" to "+receiver);
|
||||
} else if (line.equals("/users")) {
|
||||
ChatMessage msg = new ChatMessage(MessageType.USER_LIST, username, null, "");
|
||||
out.writeObject(msg);
|
||||
out.flush();
|
||||
} else
|
||||
{
|
||||
ChatMessage msg = new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line);
|
||||
out.writeObject(msg);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
} catch (Exception e){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
running = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (scanner != null) scanner.close();
|
||||
if (out != null) out.close();
|
||||
if (in != null) in.close();
|
||||
if (socket != null) socket.close();
|
||||
} catch (Exception e)
|
||||
{
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,34 @@
|
||||
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
|
||||
|
||||
// TODO: In an infinite loop:
|
||||
// accept an incoming client connection
|
||||
// make a new thread running ClientSession for each user.
|
||||
final int port = 12345;
|
||||
System.out.println("chat server starting on port "+port);
|
||||
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
||||
System.out.println("server is listening...");
|
||||
|
||||
while (true)
|
||||
{
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
System.out.println("new client connected from "+clientSocket.getInetAddress());
|
||||
|
||||
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||
Thread clientThread = new Thread(session);
|
||||
clientThread.start();
|
||||
}
|
||||
} catch (IOException e)
|
||||
{
|
||||
System.err.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,44 +2,119 @@ 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 String username;
|
||||
private final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private ObjectInputStream in;
|
||||
private ObjectOutputStream out;
|
||||
|
||||
|
||||
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());
|
||||
out.flush();
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
} catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
|
||||
// TODO: Welcome the user (login step)
|
||||
// Welcome the user (login step)
|
||||
// 1. Read the first object sent by the client.
|
||||
Object obj = in.readObject();
|
||||
|
||||
// 2. Check it's a ChatMessage with type LOGIN.
|
||||
if (!(obj instanceof ChatMessage))
|
||||
{
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
ChatMessage loginMsg = (ChatMessage) obj;
|
||||
if (loginMsg.getType() != MessageType.LOGIN)
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", null, "Invalid login request"));
|
||||
out.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Extract the username.
|
||||
String requestedUser = loginMsg.getContent();
|
||||
|
||||
// 4. Try to register the user via userManager.addUser(...).
|
||||
boolean success = userManager.addUser(requestedUser, this);
|
||||
|
||||
// 5. If the username is taken, send back LOGIN_FAILED and close the socket.
|
||||
if (!success)
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", null, "Username is already taken"));
|
||||
out.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...)
|
||||
// and send back LOGIN_SUCCESS.
|
||||
this.username = requestedUser;
|
||||
FileManager.createUserFolders(username);
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", null, "Welcome "+username));
|
||||
out.flush();
|
||||
System.out.println("User logged in: "+username);
|
||||
|
||||
// TODO: Main message loop
|
||||
// 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 received = in.readObject();
|
||||
if (received instanceof ChatMessage)
|
||||
{
|
||||
handleChatMessage((ChatMessage) received);
|
||||
} else if (received instanceof FileMessage)
|
||||
{
|
||||
handleFileMessage((FileMessage) received);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Disconnected: " + username);
|
||||
} finally {
|
||||
// TODO: Remove the user from UserManager so they no longer
|
||||
// Remove the user from UserManager so they no longer
|
||||
// receive broadcasts or appear in users list
|
||||
if (username != null)
|
||||
{
|
||||
userManager.removeUser(username);
|
||||
System.out.println("User removed: "+username);
|
||||
}
|
||||
try
|
||||
{
|
||||
if (socket != null && !socket.isClosed())
|
||||
{
|
||||
socket.close();
|
||||
}
|
||||
} catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,13 +122,36 @@ 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.
|
||||
// Broadcast this message to every connected client.
|
||||
for (ClientSession session : userManager.getAllSessions())
|
||||
{
|
||||
if (session != this)
|
||||
{
|
||||
session.out.writeObject(msg);
|
||||
session.out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
// 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 {
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", null,
|
||||
"User " + receiver + " is not online."));
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
// Reply to the requester with the list of online users.
|
||||
String list = userManager.listUsers();
|
||||
ChatMessage listMsg = new ChatMessage(MessageType.USER_LIST, "Server", null, list);
|
||||
out.writeObject(listMsg);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +164,16 @@ 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.
|
||||
// Forward the received file-message to the destination user.
|
||||
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
|
||||
if (receiver != null)
|
||||
{
|
||||
receiver.out.writeObject(fileMsg);
|
||||
receiver.out.flush();
|
||||
} else
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", null, "Cannot send file; user "+fileMsg.getReceiver()+" is offline"));
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user