forked from AdvancedProgramming1404/HW-10-Socket-Programming
Add base files
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package com.university.chat.Client;
|
||||
|
||||
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)
|
||||
|
||||
@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.
|
||||
} catch (Exception e){
|
||||
System.out.println("Disconnected from server");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.university.chat.Client;
|
||||
|
||||
public class TransferProgress {
|
||||
|
||||
private final long total;
|
||||
private final long startTime;
|
||||
private static final int WIDTH = 30;
|
||||
|
||||
public TransferProgress(long total) {
|
||||
this.total = total;
|
||||
this.startTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void update(long current) {
|
||||
|
||||
double percent = (double) current / total;
|
||||
int filled = (int) (percent * WIDTH);
|
||||
|
||||
StringBuilder bar = new StringBuilder("[");
|
||||
for (int i = 0; i < WIDTH; i++) {
|
||||
bar.append(i < filled ? "█" : " ");
|
||||
}
|
||||
bar.append("]");
|
||||
|
||||
long elapsed = System.currentTimeMillis() - startTime;
|
||||
double speed = current / 1024.0 / 1024.0 / (elapsed / 1000.0 + 0.001);
|
||||
|
||||
System.out.printf("\r%s %3d%% | %.2f MB/s",
|
||||
bar,
|
||||
(int) (percent * 100),
|
||||
speed);
|
||||
|
||||
if (current >= total) {
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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.
|
||||
|
||||
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){
|
||||
System.out.println("command failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.university.chat.Common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class ChatMessage implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private MessageType type;
|
||||
private String sender;
|
||||
private String receiver;
|
||||
private String content;
|
||||
|
||||
public ChatMessage(MessageType type, String sender, String receiver, String content) {
|
||||
this.type = type;
|
||||
this.sender = sender;
|
||||
this.receiver = receiver;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public MessageType getType() { return type; }
|
||||
public String getSender() { return sender; }
|
||||
public String getReceiver() { return receiver; }
|
||||
public String getContent() { return content; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.university.chat.Common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class FileMessage implements Serializable {
|
||||
|
||||
private static final long SerialVersionUID = 1L;
|
||||
|
||||
private String sender;
|
||||
private String receiver;
|
||||
private String filename;
|
||||
private byte[] data;
|
||||
|
||||
public FileMessage(String sender, String receiver, String filename, byte[] data) {
|
||||
this.sender = sender;
|
||||
this.receiver = receiver;
|
||||
this.filename = filename;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public String getReceiver() {
|
||||
return receiver;
|
||||
}
|
||||
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
|
||||
public byte[] getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.university.chat.Common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public enum MessageType implements Serializable {
|
||||
LOGIN,
|
||||
LOGIN_SUCCESS,
|
||||
LOGIN_FAILED,
|
||||
PUBLIC_MESSAGE,
|
||||
PRIVATE_MESSAGE,
|
||||
USER_LIST,
|
||||
FILE_TRANSFER
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
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 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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import com.university.chat.Common.ChatMessage;
|
||||
import com.university.chat.Common.FileMessage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
|
||||
public class ClientSession implements Runnable {
|
||||
|
||||
private String username;
|
||||
|
||||
public ClientSession(Socket socket, UserManager userManager) {
|
||||
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
|
||||
// and an ObjectInputStream from socket.getInputStream().
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
|
||||
// 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.
|
||||
|
||||
// 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).
|
||||
|
||||
} 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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||
switch (msg.getType()) {
|
||||
case PUBLIC_MESSAGE -> {
|
||||
// TODO: Broadcast this message to every connected client.
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
||||
// Storing the file
|
||||
var sentPath = FileManager.getSentPath(fileMsg.getSender(), fileMsg.getFilename());
|
||||
var recvPath = FileManager.getReceivedPath(fileMsg.getReceiver(), fileMsg.getFilename());
|
||||
|
||||
Files.write(sentPath, fileMsg.getData());
|
||||
Files.write(recvPath, fileMsg.getData());
|
||||
|
||||
// TODO: Forward the received file-message to the destination user.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
private static final String BASE_DIR = "server_data";
|
||||
|
||||
public static void createUserFolders(String username) throws IOException {
|
||||
Path userPath = Paths.get(BASE_DIR, username);
|
||||
Files.createDirectories(userPath.resolve("received"));
|
||||
Files.createDirectories(userPath.resolve("sent"));
|
||||
}
|
||||
|
||||
public static Path getReceivedPath(String username, String filename) {
|
||||
return Paths.get(BASE_DIR, username, "received", filename);
|
||||
}
|
||||
|
||||
public static Path getSentPath(String username, String filename) {
|
||||
return Paths.get(BASE_DIR, username, "sent", filename);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class UserManager {
|
||||
|
||||
private final ConcurrentHashMap<String, ClientSession> users = new ConcurrentHashMap<>();
|
||||
|
||||
public boolean addUser(String username, ClientSession session) {
|
||||
return users.putIfAbsent(username, session) == null;
|
||||
}
|
||||
|
||||
public void removeUser(String username) {
|
||||
users.remove(username);
|
||||
}
|
||||
|
||||
public ClientSession getUser(String username) {
|
||||
return users.get(username);
|
||||
}
|
||||
|
||||
public String listUsers() {
|
||||
return users.keySet().toString();
|
||||
}
|
||||
|
||||
public Iterable<ClientSession> getAllSessions() {
|
||||
return users.values();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user