forked from AdvancedProgramming1404/HW-10-Socket-Programming
Implement TODOS, chat client, chat server, server listener and client session #1
@@ -1,20 +1,32 @@
|
|||||||
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 final ObjectInputStream in;
|
||||||
|
|
||||||
|
public ServerListener(ObjectInputStream in) {
|
||||||
|
this.in = in;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
// TODO: In an infinite loop read objects from the server
|
while (true) {
|
||||||
// - if it's a ChatMessage -> print "<sender>: <content>"
|
Object received = in.readObject();
|
||||||
// - if it's a FileMessage -> print that a file was received
|
|
||||||
// (filename + sender), it's already
|
if (received instanceof ChatMessage msg) {
|
||||||
// saved to disk by the server.
|
System.out.println(msg.getSender() + ": " + msg.getContent());
|
||||||
} catch (Exception e){
|
} else if (received instanceof FileMessage fileMsg) {
|
||||||
|
System.out.println("Received file '" + fileMsg.getFilename() + "' from " + fileMsg.getSender());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("Disconnected from server");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,77 @@
|
|||||||
package com.university.chat.Client;
|
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.nio.file.Paths;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
public class chatClient {
|
public class chatClient {
|
||||||
public static void main() {
|
public static void main() {
|
||||||
// TODO: Connecting to the server
|
String host = "localhost";
|
||||||
// 1. Create a socket and connect to the server
|
int port = 5000;
|
||||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
Scanner scanner = new Scanner(System.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 {
|
||||||
try {
|
Socket socket = new Socket(host, port);
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
out.flush();
|
||||||
// - "/users" -> build & send a USER_LIST request
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
|
||||||
// (you can use TransferProgress
|
System.out.print("Enter your username: ");
|
||||||
// to show progress)
|
String username = scanner.nextLine();
|
||||||
// and send it as a FileMessage
|
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
|
||||||
// Remember to flush() the output stream after writeObject().
|
out.flush();
|
||||||
} catch (Exception e){
|
|
||||||
System.out.println("command failed: " + e.getMessage());
|
Thread listenerThread = new Thread(new ServerListener(in));
|
||||||
|
listenerThread.start();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
String line = scanner.nextLine();
|
||||||
|
|
||||||
|
if (line.startsWith("/msg ")) {
|
||||||
|
String[] parts = line.substring(5).split(" ", 2);
|
||||||
|
String receiver = parts[0];
|
||||||
|
String text = parts.length > 1 ? parts[1] : "";
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, receiver, text));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else if (line.equals("/users")) {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.USER_LIST, username, null, null));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else if (line.startsWith("/sendfile ")) {
|
||||||
|
String[] parts = line.substring(10).split(" ", 2);
|
||||||
|
String receiver = parts[0];
|
||||||
|
String path = parts[1];
|
||||||
|
|
||||||
|
Path filePath = Paths.get(path);
|
||||||
|
byte[] data = Files.readAllBytes(filePath);
|
||||||
|
String filename = filePath.getFileName().toString();
|
||||||
|
|
||||||
|
out.writeObject(new FileMessage(username, receiver, filename, data));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PUBLIC_MESSAGE, username, null, line));
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("command failed: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Could not connect to server: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,27 @@
|
|||||||
package com.university.chat.Server;
|
package com.university.chat.Server;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
|
||||||
public class ChatServer {
|
public class ChatServer {
|
||||||
// TODO: declare a single shared UserManager instance (static final)
|
|
||||||
// This MUST be shared by all ClientSession threads so that
|
private static final UserManager userManager = new UserManager();
|
||||||
// broadcasting and private messaging work correctly.
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
int port = 5000;
|
||||||
|
|
||||||
// TODO: In an infinite loop:
|
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
||||||
// accept an incoming client connection
|
System.out.println("Server started on port " + port);
|
||||||
// make a new thread running ClientSession for each user.
|
|
||||||
|
while (true) {
|
||||||
|
Socket clientSocket = serverSocket.accept();
|
||||||
|
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||||
|
Thread thread = new Thread(session);
|
||||||
|
thread.start();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Server error: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,70 +2,107 @@ 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.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
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 String username;
|
private String username;
|
||||||
|
private final Socket socket;
|
||||||
|
private final UserManager userManager;
|
||||||
|
private ObjectOutputStream out;
|
||||||
|
private ObjectInputStream in;
|
||||||
|
|
||||||
public ClientSession(Socket socket, UserManager userManager) {
|
public ClientSession(Socket socket, UserManager userManager) {
|
||||||
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
|
this.socket = socket;
|
||||||
// and an ObjectInputStream from socket.getInputStream().
|
this.userManager = userManager;
|
||||||
|
try {
|
||||||
|
this.out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
this.out.flush();
|
||||||
|
this.in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Failed to set up streams: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
|
Object first = in.readObject();
|
||||||
|
if (first instanceof ChatMessage loginMsg && loginMsg.getType() == MessageType.LOGIN) {
|
||||||
|
username = loginMsg.getSender();
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
if (!userManager.addUser(username, this)) {
|
||||||
// 1. Read the first object sent by the client.
|
sendMessage(new ChatMessage(MessageType.LOGIN_FAILED, "Server", username, "Username already taken"));
|
||||||
// 2. Check it's a ChatMessage with type LOGIN.
|
socket.close();
|
||||||
// 3. Extract the username.
|
return;
|
||||||
// 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
|
FileManager.createUserFolders(username);
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
sendMessage(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", username, "Welcome, " + username + "!"));
|
||||||
// - if it's a ChatMessage -> call handleChatMessage(msg)
|
} else {
|
||||||
// - if it's a FileMessage -> call handleFileMessage(fileMsg)
|
socket.close();
|
||||||
// Keep looping until the connection is closed (an exception will be thrown).
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
Object received = in.readObject();
|
||||||
|
if (received instanceof ChatMessage msg) {
|
||||||
|
handleChatMessage(msg);
|
||||||
|
} else if (received instanceof FileMessage fileMsg) {
|
||||||
|
handleFileMessage(fileMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected: " + username);
|
System.out.println("Disconnected: " + username);
|
||||||
} finally {
|
} finally {
|
||||||
// TODO: Remove the user from UserManager so they no longer
|
if (username != null) {
|
||||||
// receive broadcasts or appear in users list
|
userManager.removeUser(username);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void sendMessage(Object obj) throws IOException {
|
||||||
|
out.writeObject(obj);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||||
switch (msg.getType()) {
|
switch (msg.getType()) {
|
||||||
case PUBLIC_MESSAGE -> {
|
case PUBLIC_MESSAGE -> {
|
||||||
// TODO: Broadcast this message to every connected client.
|
for (ClientSession session : userManager.getAllSessions()) {
|
||||||
|
session.sendMessage(msg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case PRIVATE_MESSAGE -> {
|
case PRIVATE_MESSAGE -> {
|
||||||
// TODO: Forward this message to the receiver user.
|
ClientSession receiver = userManager.getUser(msg.getReceiver());
|
||||||
|
if (receiver != null) {
|
||||||
|
receiver.sendMessage(msg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
ChatMessage reply = new ChatMessage(MessageType.USER_LIST, "Server", msg.getSender(), userManager.listUsers());
|
||||||
|
sendMessage(reply);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
private void handleFileMessage(FileMessage fileMsg) throws IOException {
|
||||||
// Storing the file
|
|
||||||
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.sendMessage(fileMsg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user