forked from AdvancedProgramming1404/HW-10-Socket-Programming
Develop #1
@@ -1,18 +1,38 @@
|
|||||||
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.ObjectInputStream;
|
||||||
|
|
||||||
public class ServerListener implements Runnable{
|
public class ServerListener implements Runnable{
|
||||||
// TODO: store the ObjectInputStream from the user socket
|
|
||||||
// (this should be the same input stream the
|
private final ObjectInputStream in;
|
||||||
// chatClient created when connecting)
|
|
||||||
|
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 msg = in.readObject();
|
||||||
// - if it's a FileMessage -> print that a file was received
|
if(msg instanceof ChatMessage chat){
|
||||||
// (filename + sender), it's already
|
if (chat.getType() == MessageType.LOGIN_SUCCESS) {
|
||||||
// saved to disk by the server.
|
System.out.println(" Login successful!");
|
||||||
|
} else if (chat.getType() == MessageType.LOGIN_FAILED) {
|
||||||
|
System.out.println(" Login failed: " + chat.getContent());
|
||||||
|
} else if (chat.getSender().equals("Server")) {
|
||||||
|
System.out.println("[Server]: " + chat.getContent());
|
||||||
|
} else {
|
||||||
|
System.out.println(chat.getSender() + ": " + chat.getContent());
|
||||||
|
}
|
||||||
|
}else if(msg instanceof FileMessage file){
|
||||||
|
System.out.println("File received: " + file.getFilename() + " from " + file.getSender());
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (Exception e){
|
} catch (Exception e){
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("Disconnected from server");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,68 @@
|
|||||||
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
|
import java.io.ObjectInputStream;
|
||||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
import java.io.ObjectOutputStream;
|
||||||
// from the socket's streams — output FIRST, then input.
|
import java.net.Socket;
|
||||||
// 2. Get the username, and send a LOGIN ChatMessage with that username
|
import java.nio.file.Files;
|
||||||
// 3. Start a new Thread running a ServerListener(in) so incoming
|
import java.nio.file.Paths;
|
||||||
// messages are handled concurrently.
|
import java.util.Scanner;
|
||||||
|
|
||||||
while (true){
|
public class chatClient {
|
||||||
try {
|
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
public static void main(String[] args) {
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
try (Socket socket = new Socket("localhost", 12345)) {
|
||||||
// - "/users" -> build & send a USER_LIST request
|
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
Scanner scanner = new Scanner(System.in);
|
||||||
// (you can use TransferProgress
|
System.out.println("Connected to server");
|
||||||
// to show progress)
|
|
||||||
// and send it as a FileMessage
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
out.flush();
|
||||||
// Remember to flush() the output stream after writeObject().
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
||||||
} catch (Exception e){
|
|
||||||
System.out.println("command failed: " + e.getMessage());
|
|
||||||
|
System.out.println("Enter username: ");
|
||||||
|
String username = scanner.nextLine().trim();
|
||||||
|
|
||||||
|
Thread listenerThread = new Thread(new ServerListener(in));
|
||||||
|
listenerThread.setDaemon(true);
|
||||||
|
listenerThread.start();
|
||||||
|
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN, username, null, username));
|
||||||
|
out.flush();
|
||||||
|
|
||||||
|
Thread.sleep(300);
|
||||||
|
|
||||||
|
System.out.println("Login successful " + username);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
String line = scanner.nextLine();
|
||||||
|
|
||||||
|
if (line.startsWith("/msg ")){
|
||||||
|
String [] parts = line.split(" ", 3);
|
||||||
|
if (parts.length == 3){
|
||||||
|
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, username, parts[1], parts[2]));
|
||||||
|
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.split(" ", 3);
|
||||||
|
if (parts.length == 3){
|
||||||
|
byte[] data = Files.readAllBytes(Paths.get(parts[2]));
|
||||||
|
out.writeObject(new FileMessage(username, parts[1], Paths.get(parts[2]).getFileName().toString(), 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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
package com.university.chat.Server;
|
package com.university.chat.Server;
|
||||||
|
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
|
||||||
public class ChatServer {
|
public class ChatServer {
|
||||||
// TODO: declare a single shared UserManager instance (static final)
|
public static final UserManager userManager = new UserManager();
|
||||||
// This MUST be shared by all ClientSession threads so that
|
|
||||||
// broadcasting and private messaging work correctly.
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
try(ServerSocket serverSocket = new ServerSocket(12345)){
|
||||||
|
System.out.println("Server started on port 12345");
|
||||||
// TODO: In an infinite loop:
|
while (true){
|
||||||
// accept an incoming client connection
|
Socket clientSocket = serverSocket.accept();
|
||||||
// make a new thread running ClientSession for each user.
|
new Thread(new ClientSession(clientSocket, userManager)).start();
|
||||||
|
}
|
||||||
|
}catch (Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,70 +2,115 @@ 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;
|
||||||
|
private boolean isLogeIn = false;
|
||||||
|
|
||||||
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.in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
}catch (IOException e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
|
ChatMessage loginMsg = (ChatMessage) in.readObject();
|
||||||
|
if(loginMsg.getType() == MessageType.LOGIN){
|
||||||
|
this.username = loginMsg.getContent();
|
||||||
|
if (userManager.addUser(username, this)){
|
||||||
|
FileManager.createUserFolders(username);
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", null, "Welcome"));
|
||||||
|
out.flush();
|
||||||
|
isLogeIn = true;
|
||||||
|
System.out.println("User logged in: " + username);
|
||||||
|
}else{
|
||||||
|
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", null, "User taken"));
|
||||||
|
out.flush();
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
while (true) {
|
||||||
// 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) handleChatMessage((ChatMessage) obj);
|
||||||
// 3. Extract the username.
|
else if (obj instanceof FileMessage) handleFileMessage((FileMessage) obj);
|
||||||
// 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) {
|
} 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 && userManager.getUser(username) == this){
|
||||||
// receive broadcasts or appear in users list
|
userManager.removeUser(username);
|
||||||
}
|
System.out.println("User removed: " + username);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (socket != null && socket.isClosed()){
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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.
|
System.out.println("Broadcasting from " + msg.getSender());
|
||||||
|
for (ClientSession s : userManager.getAllSessions()){
|
||||||
|
if(s != this && s.isLogeIn) s.sendMessage(msg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case PRIVATE_MESSAGE -> {
|
case PRIVATE_MESSAGE -> {
|
||||||
// TODO: Forward this message to the receiver user.
|
System.out.println("Private message from " + msg.getSender() + "to " + msg.getReceiver());
|
||||||
|
ClientSession target = userManager.getUser(msg.getReceiver());
|
||||||
|
if(target != null && target != this && target.isLogeIn) {
|
||||||
|
target.sendMessage(msg);
|
||||||
|
}else if(target == this){
|
||||||
|
sendMessage(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server" , username, "You cannot message yourself"));
|
||||||
|
}else {
|
||||||
|
sendMessage(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server" , username, "User not found: " +msg.getReceiver()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
String usersList = String.join(", ", userManager.listUsers());
|
||||||
|
sendMessage(new ChatMessage(MessageType.USER_LIST, "Server", username, usersList));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 target = userManager.getUser(fileMsg.getReceiver());
|
||||||
|
if (target != null && target.isLogeIn) target.sendMessage(fileMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendMessage(Object msg) throws IOException{
|
||||||
|
if (out != null){
|
||||||
|
out.writeObject(msg);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user