Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74dca477bc |
Generated
+1
-3
@@ -8,7 +8,5 @@
|
|||||||
</list>
|
</list>
|
||||||
</option>
|
</option>
|
||||||
</component>
|
</component>
|
||||||
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK">
|
<component name="ProjectRootManager" version="2" project-jdk-name="21" project-jdk-type="JavaSDK" />
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
|
||||||
</component>
|
|
||||||
</project>
|
</project>
|
||||||
@@ -1,20 +1,54 @@
|
|||||||
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
|
|
||||||
// chatClient created when connecting)
|
import java.io.ObjectInputStream;
|
||||||
|
|
||||||
|
public class ServerListener implements Runnable
|
||||||
|
{
|
||||||
|
|
||||||
|
private ObjectInputStream in;
|
||||||
|
|
||||||
|
public ServerListener(ObjectInputStream in)
|
||||||
|
{
|
||||||
|
this.in = in;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run()
|
||||||
try {
|
{
|
||||||
// TODO: In an infinite loop read objects from the server
|
try
|
||||||
// - if it's a ChatMessage -> print "<sender>: <content>"
|
{
|
||||||
// - if it's a FileMessage -> print that a file was received
|
while (true)
|
||||||
// (filename + sender), it's already
|
{
|
||||||
// saved to disk by the server.
|
Object obj = in.readObject();
|
||||||
} catch (Exception e){
|
|
||||||
System.out.println("Disconnected from server");
|
if (obj instanceof ChatMessage msg)
|
||||||
|
{
|
||||||
|
String content = msg.getContent();
|
||||||
|
|
||||||
|
if (content != null && !content.trim().isEmpty())
|
||||||
|
{
|
||||||
|
if (msg.getSender().equals("Server"))
|
||||||
|
{
|
||||||
|
System.out.println("[Server]: " + content);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
System.out.println("[" + msg.getSender() + "]: " + content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (obj instanceof FileMessage fileMsg)
|
||||||
|
{
|
||||||
|
System.out.println("[File received from " + fileMsg.getSender() + "]: " + fileMsg.getFilename());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
System.out.println("Connection to server lost.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,27 @@
|
|||||||
package com.university.chat.Client;
|
package com.university.chat.Client;
|
||||||
|
|
||||||
public class TransferProgress {
|
public class TransferProgress
|
||||||
|
{
|
||||||
|
|
||||||
private final long total;
|
private final long total;
|
||||||
private final long startTime;
|
private final long startTime;
|
||||||
private static final int WIDTH = 30;
|
private static final int WIDTH = 30;
|
||||||
|
|
||||||
public TransferProgress(long total) {
|
public TransferProgress(long total)
|
||||||
|
{
|
||||||
this.total = total;
|
this.total = total;
|
||||||
this.startTime = System.currentTimeMillis();
|
this.startTime = System.currentTimeMillis();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void update(long current) {
|
public void update(long current)
|
||||||
|
{
|
||||||
|
|
||||||
double percent = (double) current / total;
|
double percent = (double) current / total;
|
||||||
int filled = (int) (percent * WIDTH);
|
int filled = (int) (percent * WIDTH);
|
||||||
|
|
||||||
StringBuilder bar = new StringBuilder("[");
|
StringBuilder bar = new StringBuilder("[");
|
||||||
for (int i = 0; i < WIDTH; i++) {
|
for (int i = 0; i < WIDTH; i++)
|
||||||
|
{
|
||||||
bar.append(i < filled ? "█" : " ");
|
bar.append(i < filled ? "█" : " ");
|
||||||
}
|
}
|
||||||
bar.append("]");
|
bar.append("]");
|
||||||
@@ -30,7 +34,8 @@ public class TransferProgress {
|
|||||||
(int) (percent * 100),
|
(int) (percent * 100),
|
||||||
speed);
|
speed);
|
||||||
|
|
||||||
if (current >= total) {
|
if (current >= total)
|
||||||
|
{
|
||||||
System.out.println();
|
System.out.println();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,231 @@
|
|||||||
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.File;
|
||||||
try {
|
import java.io.FileInputStream;
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
import java.io.ObjectInputStream;
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
import java.io.ObjectOutputStream;
|
||||||
// - "/users" -> build & send a USER_LIST request
|
import java.net.Socket;
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
import java.util.Scanner;
|
||||||
// (you can use TransferProgress
|
|
||||||
// to show progress)
|
public class chatClient
|
||||||
// and send it as a FileMessage
|
{
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
|
||||||
// Remember to flush() the output stream after writeObject().
|
private static final String SERVER_HOST = "localhost";
|
||||||
} catch (Exception e){
|
private static final int SERVER_PORT = 5000;
|
||||||
System.out.println("command failed: " + e.getMessage());
|
|
||||||
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
|
||||||
|
System.out.println("Connected to server.");
|
||||||
|
|
||||||
|
|
||||||
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
out.flush();
|
||||||
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
|
||||||
|
System.out.print("Enter username: ");
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
String username = scanner.nextLine();
|
||||||
|
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN, username, "", ""));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
Thread listenerThread = new Thread(new ServerListener(in));
|
||||||
|
listenerThread.start();
|
||||||
|
|
||||||
|
System.out.println("You can now chat.");
|
||||||
|
System.out.println("Commands:");
|
||||||
|
System.out.println("/msg <username> <message>");
|
||||||
|
System.out.println("/users");
|
||||||
|
System.out.println("/sendfile <username> <filepath>");
|
||||||
|
System.out.println("Anything else will be sent as a public message.");
|
||||||
|
System.out.print("> ");
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
String line = scanner.nextLine();
|
||||||
|
|
||||||
|
if (line == null || line.trim().isEmpty())
|
||||||
|
{
|
||||||
|
System.out.print("> ");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
line = line.trim();
|
||||||
|
|
||||||
|
if (line.startsWith("/msg "))
|
||||||
|
{
|
||||||
|
handlePrivateMessage(line, username, out);
|
||||||
|
}
|
||||||
|
else if (line.equals("/users"))
|
||||||
|
{
|
||||||
|
handleUserListRequest(username, out);
|
||||||
|
}
|
||||||
|
else if (line.startsWith("/sendfile "))
|
||||||
|
{
|
||||||
|
handleFileSend(line, username, out);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
handlePublicMessage(line, username, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.print("> ");
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
System.out.println("command failed: " + e.getMessage());
|
||||||
|
System.out.print("> ");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
System.out.println("Could not connect to server: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static void handlePrivateMessage(String line, String username, ObjectOutputStream out) throws Exception {
|
||||||
|
|
||||||
|
String[] parts = line.split(" ", 3);
|
||||||
|
|
||||||
|
if (parts.length < 3)
|
||||||
|
{
|
||||||
|
System.out.println("Usage: /msg <username> <message>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String receiver = parts[1];
|
||||||
|
String messageText = parts[2];
|
||||||
|
|
||||||
|
ChatMessage privateMessage = new ChatMessage(
|
||||||
|
MessageType.PRIVATE_MESSAGE,
|
||||||
|
username,
|
||||||
|
messageText,
|
||||||
|
receiver
|
||||||
|
);
|
||||||
|
|
||||||
|
out.writeObject(privateMessage);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void handleUserListRequest(String username, ObjectOutputStream out) throws Exception
|
||||||
|
{
|
||||||
|
ChatMessage userListRequest = new ChatMessage(
|
||||||
|
MessageType.USER_LIST,
|
||||||
|
username,
|
||||||
|
null,
|
||||||
|
""
|
||||||
|
);
|
||||||
|
|
||||||
|
out.writeObject(userListRequest);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void handlePublicMessage(String line, String username, ObjectOutputStream out) throws Exception
|
||||||
|
{
|
||||||
|
ChatMessage publicMessage = new ChatMessage(
|
||||||
|
MessageType.PUBLIC_MESSAGE,
|
||||||
|
username,
|
||||||
|
null,
|
||||||
|
line
|
||||||
|
);
|
||||||
|
|
||||||
|
out.writeObject(publicMessage);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void handleFileSend(String line, String username, ObjectOutputStream out) throws Exception
|
||||||
|
{
|
||||||
|
|
||||||
|
String[] parts = line.split(" ", 3);
|
||||||
|
|
||||||
|
if (parts.length < 3)
|
||||||
|
{
|
||||||
|
System.out.println("Usage: /sendfile <username> <filepath>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String receiver = parts[1];
|
||||||
|
String filePath = parts[2];
|
||||||
|
|
||||||
|
File file = new File(filePath);
|
||||||
|
|
||||||
|
if (!file.exists())
|
||||||
|
{
|
||||||
|
System.out.println("File does not exist: " + filePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!file.isFile())
|
||||||
|
{
|
||||||
|
System.out.println("This path is not a file: " + filePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long totalSize = file.length();
|
||||||
|
|
||||||
|
TransferProgress progress = new TransferProgress(totalSize);
|
||||||
|
|
||||||
|
byte[] data = new byte[(int) totalSize];
|
||||||
|
|
||||||
|
FileInputStream fis = new FileInputStream(file);
|
||||||
|
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
int bytesRead;
|
||||||
|
int totalRead = 0;
|
||||||
|
|
||||||
|
while ((bytesRead = fis.read(buffer)) != -1)
|
||||||
|
{
|
||||||
|
|
||||||
|
System.arraycopy(buffer, 0, data, totalRead, bytesRead);
|
||||||
|
totalRead += bytesRead;
|
||||||
|
|
||||||
|
progress.update(totalRead);
|
||||||
|
}
|
||||||
|
|
||||||
|
fis.close();
|
||||||
|
|
||||||
|
FileMessage fileMessage = new FileMessage(
|
||||||
|
username,
|
||||||
|
receiver,
|
||||||
|
file.getName(),
|
||||||
|
data
|
||||||
|
);
|
||||||
|
|
||||||
|
out.writeObject(fileMessage);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
System.out.println("File sent successfully: " + file.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readFileToByteArray(File file) throws Exception
|
||||||
|
{
|
||||||
|
byte[] data = new byte[(int) file.length()];
|
||||||
|
|
||||||
|
FileInputStream fis = new FileInputStream(file);
|
||||||
|
|
||||||
|
int totalRead = 0;
|
||||||
|
int bytesRead;
|
||||||
|
|
||||||
|
while (totalRead < data.length && (bytesRead = fis.read(data, totalRead, data.length - totalRead)) != -1)
|
||||||
|
{
|
||||||
|
totalRead += bytesRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
fis.close();
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,8 @@ package com.university.chat.Common;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
public class ChatMessage implements Serializable {
|
public class ChatMessage implements Serializable
|
||||||
|
{
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -11,7 +12,8 @@ public class ChatMessage implements Serializable {
|
|||||||
private String receiver;
|
private String receiver;
|
||||||
private String content;
|
private String content;
|
||||||
|
|
||||||
public ChatMessage(MessageType type, String sender, String receiver, String content) {
|
public ChatMessage(MessageType type, String sender, String receiver, String content)
|
||||||
|
{
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.sender = sender;
|
this.sender = sender;
|
||||||
this.receiver = receiver;
|
this.receiver = receiver;
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ package com.university.chat.Common;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
public class FileMessage implements Serializable {
|
public class FileMessage implements Serializable
|
||||||
|
{
|
||||||
|
|
||||||
private static final long SerialVersionUID = 1L;
|
private static final long SerialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -11,26 +12,31 @@ public class FileMessage implements Serializable {
|
|||||||
private String filename;
|
private String filename;
|
||||||
private byte[] data;
|
private byte[] data;
|
||||||
|
|
||||||
public FileMessage(String sender, String receiver, String filename, byte[] data) {
|
public FileMessage(String sender, String receiver, String filename, byte[] data)
|
||||||
|
{
|
||||||
this.sender = sender;
|
this.sender = sender;
|
||||||
this.receiver = receiver;
|
this.receiver = receiver;
|
||||||
this.filename = filename;
|
this.filename = filename;
|
||||||
this.data = data;
|
this.data = data;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getSender() {
|
public String getSender()
|
||||||
|
{
|
||||||
return sender;
|
return sender;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getReceiver() {
|
public String getReceiver()
|
||||||
|
{
|
||||||
return receiver;
|
return receiver;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFilename() {
|
public String getFilename()
|
||||||
|
{
|
||||||
return filename;
|
return filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
public byte[] getData() {
|
public byte[] getData()
|
||||||
|
{
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ package com.university.chat.Common;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
public enum MessageType implements Serializable {
|
public enum MessageType implements Serializable
|
||||||
|
{
|
||||||
LOGIN,
|
LOGIN,
|
||||||
LOGIN_SUCCESS,
|
LOGIN_SUCCESS,
|
||||||
LOGIN_FAILED,
|
LOGIN_FAILED,
|
||||||
|
|||||||
@@ -1,15 +1,53 @@
|
|||||||
package com.university.chat.Server;
|
package com.university.chat.Server;
|
||||||
|
|
||||||
public class ChatServer {
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
|
||||||
|
public class ChatServer
|
||||||
|
{
|
||||||
|
private static final UserManager userManager = new UserManager();
|
||||||
|
|
||||||
|
private static final int PORT = 5000;
|
||||||
// TODO: declare a single shared UserManager instance (static final)
|
// TODO: declare a single shared UserManager instance (static final)
|
||||||
// This MUST be shared by all ClientSession threads so that
|
// This MUST be shared by all ClientSession threads so that
|
||||||
// broadcasting and private messaging work correctly.
|
// broadcasting and private messaging work correctly.
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
|
||||||
|
System.out.println("Chat server starting on port " + PORT + "...");
|
||||||
|
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(PORT))
|
||||||
|
{
|
||||||
|
|
||||||
|
System.out.println("Server started. Waiting for clients...");
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
|
||||||
|
Socket clientSocket = serverSocket.accept();
|
||||||
|
|
||||||
|
System.out.println("New client connected: "
|
||||||
|
+ clientSocket.getInetAddress());
|
||||||
|
|
||||||
|
ClientSession session =
|
||||||
|
new ClientSession(clientSocket, userManager);
|
||||||
|
|
||||||
|
Thread thread = new Thread(session);
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
System.out.println("Server error: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
// TODO: Create a ServerSocket
|
// TODO: Create a ServerSocket
|
||||||
|
|
||||||
// TODO: In an infinite loop:
|
// TODO: In an infinite loop:
|
||||||
// accept an incoming client connection
|
// accept an incoming client connection
|
||||||
// make a new thread running ClientSession for each user.
|
// make a new thread running ClientSession for each user.
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,70 +2,152 @@ 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.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
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 final Socket socket;
|
||||||
|
private final UserManager userManager;
|
||||||
|
private ObjectOutputStream out;
|
||||||
|
private ObjectInputStream in;
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
public ClientSession(Socket socket, UserManager userManager) {
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run()
|
||||||
try {
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
this.out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
this.out.flush();
|
||||||
|
this.in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
Object obj = in.readObject();
|
||||||
// 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 (obj instanceof ChatMessage loginMsg && loginMsg.getType() == MessageType.LOGIN)
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
{
|
||||||
// - if it's a ChatMessage -> call handleChatMessage(msg)
|
String requestedUsername = loginMsg.getSender();
|
||||||
// - if it's a FileMessage -> call handleFileMessage(fileMsg)
|
|
||||||
// Keep looping until the connection is closed (an exception will be thrown).
|
if (userManager.addUser(requestedUsername, this))
|
||||||
|
{
|
||||||
|
this.username = requestedUsername;
|
||||||
|
FileManager.createUserFolders(this.username);
|
||||||
|
|
||||||
|
send(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", "Welcome to the chat system!", ""));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
send(new ChatMessage(MessageType.LOGIN_FAILED, "Server", "Username already taken.", ""));
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
Object receivedObj = in.readObject();
|
||||||
|
|
||||||
|
if (receivedObj instanceof ChatMessage msg)
|
||||||
|
{
|
||||||
|
handleChatMessage(msg);
|
||||||
|
}
|
||||||
|
else if (receivedObj 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
|
|
||||||
}
|
}
|
||||||
}
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
System.out.println("Disconnected: " + (username != null ? username : "Unknown client"));
|
||||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
}
|
||||||
switch (msg.getType()) {
|
finally
|
||||||
case PUBLIC_MESSAGE -> {
|
{
|
||||||
// TODO: Broadcast this message to every connected client.
|
if (username != null)
|
||||||
|
{
|
||||||
|
userManager.removeUser(username);
|
||||||
}
|
}
|
||||||
case PRIVATE_MESSAGE -> {
|
try
|
||||||
// TODO: Forward this message to the receiver user.
|
{
|
||||||
|
socket.close();
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
catch (IOException e)
|
||||||
// TODO: Reply to the requester with the list of online users.
|
{
|
||||||
|
System.err.println("Error closing socket: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
public void send(Object msg) throws IOException
|
||||||
// Storing the file
|
{
|
||||||
|
if (out != null)
|
||||||
|
{
|
||||||
|
out.writeObject(msg);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleChatMessage(ChatMessage msg) throws IOException
|
||||||
|
{
|
||||||
|
switch (msg.getType())
|
||||||
|
{
|
||||||
|
case PUBLIC_MESSAGE ->
|
||||||
|
{
|
||||||
|
for (ClientSession session : userManager.getAllSessions())
|
||||||
|
{
|
||||||
|
session.send(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PRIVATE_MESSAGE ->
|
||||||
|
{
|
||||||
|
ClientSession receiver = userManager.getUser(msg.getReceiver());
|
||||||
|
if (receiver != null)
|
||||||
|
{
|
||||||
|
receiver.send(msg);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
send(new ChatMessage(MessageType.PUBLIC_MESSAGE, "Server", "User not found: " + msg.getReceiver(), username));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case USER_LIST ->
|
||||||
|
{
|
||||||
|
String userListStr = userManager.listUsers();
|
||||||
|
send(new ChatMessage(MessageType.USER_LIST, "Server", userListStr, username));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleFileMessage(FileMessage fileMsg) throws IOException
|
||||||
|
{
|
||||||
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.send(fileMsg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user