debug and test

This commit is contained in:
2026-06-28 10:02:55 +03:30
parent faac68e30b
commit 027ead9fa9
4 changed files with 99 additions and 49 deletions
@@ -19,24 +19,24 @@ public class ServerListener implements Runnable{
try { try {
while (true){ while (true){
Object objectInput = in.readObject(); Object objectInput = in.readObject();
if(objectInput instanceof ChatMessage){ if(objectInput instanceof ChatMessage msg){
if(((ChatMessage) objectInput).getType() == MessageType.LOGIN_SUCCESS){ if(msg.getType() == MessageType.LOGIN_SUCCESS){
System.out.println("Login success"); System.out.println("Login success");
} else if (((ChatMessage) objectInput).getType() == MessageType.LOGIN_FAILED) { } else if (msg.getType() == MessageType.LOGIN_FAILED) {
System.out.println("Login Failed"); System.out.println("Login Failed");
} }
System.out.println(((ChatMessage) objectInput).getSender()+ ": " + System.out.println(msg.getSender()+ ": " + msg.getContent());
((ChatMessage) objectInput).getContent());
} }
else if(objectInput instanceof FileMessage){ else if(objectInput instanceof FileMessage filemsg){
System.out.println("File name: " + ((FileMessage) objectInput).getFilename() System.out.println("File name: "+ filemsg.getFilename()
+ "from : "+ ((FileMessage) objectInput).getSender()+ " recived."); +"from : "+ filemsg.getSender()+ " recived.");
} }
} }
} catch (Exception e){ } catch (Exception e){
System.out.println("Disconnected from server"); System.out.println("Disconnected from server");
System.out.println(e.getMessage());
} }
} }
} }
@@ -26,15 +26,15 @@ public class chatClient {
out.flush(); out.flush();
ServerListener serverListener = new ServerListener(in); ServerListener serverListener = new ServerListener(in);
Thread t = new Thread(); Thread t = new Thread(serverListener);
t.start(); t.start();
while (true){ while (true){
try { try {
String promt = input.nextLine().trim(); String promt = input.nextLine();
promt = promt.replace("<", "").replace(">", ""); //promt = promt.replace("<", "").replace(">", "");
String[] parts = promt.split(" " , 3); String[] parts = promt.split(" " , 3);
@@ -42,19 +42,24 @@ public class chatClient {
case "/msg": case "/msg":
{ {
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE , username out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE , username
, parts[1] , parts[2])); , parts[1] ," \'private\' " + parts[2]));
break; break;
} }
case "/users": case "/users":
{ {
out.writeObject(new ChatMessage(MessageType.USER_LIST ,username out.writeObject(new ChatMessage(MessageType.USER_LIST ,username
, "Server" , null)); , "Server" , null));
out.flush();
break; break;
} }
case "/sendfile": case "/sendfile":
{ {
byte[] dataofFile = Files.readAllBytes(Path.of(parts[2])); File file = new File(String.valueOf(Path.of(parts[2])));
out.writeObject(new FileMessage(username , parts[1] , parts[2] , dataofFile )); String filename = file.getName();
byte[] fileContent = Files.readAllBytes(file.toPath());
out.writeObject(new FileMessage(username , parts[1] , parts[2] , fileContent ));
out.flush();
System.out.println("file send.");
break; break;
} }
case "/quit": case "/quit":
@@ -7,22 +7,26 @@ import java.net.Socket;
public class ChatServer { public class ChatServer {
private static final UserManager users = new UserManager(); private static final UserManager users = new UserManager();
private static ServerSocket srvSocket;
public static void main(String[] args) throws IOException {
public static void main(String[] args) {
try { try {
ServerSocket srvSocket = new ServerSocket(5000); srvSocket = new ServerSocket(5000);
System.out.println("Servre start.");
while (true){ while (true){
Socket clientsocket = srvSocket.accept(); Socket clientsocket = srvSocket.accept();
ClientSession clientSession = new ClientSession(clientsocket , users); ClientSession clientSession = new ClientSession(clientsocket , users);
Thread t = new Thread(clientSession); Thread t = new Thread(clientSession);
t.start(); t.start();
} }
} catch (IOException e) { } catch (IOException e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
}finally {
srvSocket.close();
} }
} }
} }
@@ -4,19 +4,23 @@ 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 com.university.chat.Common.MessageType;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.net.Socket; import java.net.Socket;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ClientSession implements Runnable { public class ClientSession implements Runnable {
private String username; private String username;
private ObjectOutputStream out; private ObjectOutputStream out = null;
private ObjectInputStream in; private ObjectInputStream in = null;
private Socket socket; private final Socket socket;
private UserManager userManage; private final UserManager userManage;
private final Lock L = new ReentrantLock();
@@ -26,24 +30,19 @@ public class ClientSession implements Runnable {
try { try {
out = new ObjectOutputStream(socket.getOutputStream()); out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream()); in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); System.out.println(e.getMessage());
} }
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
// and an ObjectInputStream from socket.getInputStream().
} }
@Override @Override
public void run() { public void run() {
try { try {
ChatMessage loginmsg = (ChatMessage) in.readObject(); ChatMessage loginmsg = (ChatMessage) in.readObject();
String username = loginmsg.getSender(); username = loginmsg.getSender();
if(loginmsg.getType() != MessageType.LOGIN){ if(loginmsg.getType() != MessageType.LOGIN){
@@ -53,32 +52,39 @@ public class ClientSession implements Runnable {
return; return;
} }
FileManager.createUserFolders(username);
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS , "server" , out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS , "server" ,
null , "welcome to messanger")); username , "welcome to messanger login succes"));
System.out.println(username + " connected");
userManage.addUser(username , this); userManage.addUser(username , this);
while (true){
Object inputobj = in.readObject();
if(inputobj == null){
continue;
}
if(inputobj instanceof ChatMessage msg){
handleChatMessage(msg);
} else if (inputobj instanceof FileMessage filemsg) {
handleFileMessage(filemsg);
}
}
// 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) { } catch (Exception e) {
System.out.println("Disconnected: " + username); System.out.println("Disconnected: " + username);
System.out.println(e.getMessage());
} finally { } finally {
// TODO: Remove the user from UserManager so they no longer if(username != null) {
// receive broadcasts or appear in users list userManage.removeUser(username);
}
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
} }
@@ -86,13 +92,26 @@ public class ClientSession implements Runnable {
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 cs : userManage.getAllSessions()){
if(cs != this){
cs.sendMessage(msg);
}
}
} }
case PRIVATE_MESSAGE -> { case PRIVATE_MESSAGE -> {
// TODO: Forward this message to the receiver user. ClientSession cs = userManage.getUser(msg.getReceiver());
if (cs != null) {
cs.sendMessage(msg);
}
} }
case USER_LIST -> { case USER_LIST -> {
// TODO: Reply to the requester with the list of online users. ClientSession cs = userManage.getUser(msg.getSender());
ChatMessage listReply = new ChatMessage(MessageType.USER_LIST, "server",
username, userManage.listUsers());
if (cs != null) {
cs.sendMessage(listReply);
}
} }
} }
} }
@@ -105,6 +124,28 @@ public class ClientSession implements Runnable {
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 cs = userManage.getUser(fileMsg.getReceiver());
if(cs != null){
cs.sendMessage(fileMsg);
} }
System.out.println("Server received file: " + fileMsg.getFilename() + " with size: " + fileMsg.getData().length);
}
public void sendMessage(Object object) {
try {
L.lock();
out.writeObject(object);
out.flush();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
L.unlock();
}
}
} }