complete server-side classes
This commit is contained in:
@@ -1,15 +1,34 @@
|
||||
package com.university.chat.Server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
|
||||
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.
|
||||
|
||||
private static final UserManager userManager = new UserManager();
|
||||
|
||||
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.
|
||||
final int port = 12345;
|
||||
System.out.println("chat server starting on port "+port);
|
||||
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
||||
System.out.println("server is listening...");
|
||||
|
||||
while (true)
|
||||
{
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
System.out.println("new client connected from "+clientSocket.getInetAddress());
|
||||
|
||||
ClientSession session = new ClientSession(clientSocket, userManager);
|
||||
Thread clientThread = new Thread(session);
|
||||
clientThread.start();
|
||||
}
|
||||
} catch (IOException e)
|
||||
{
|
||||
System.err.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,44 +2,118 @@ package com.university.chat.Server;
|
||||
|
||||
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;
|
||||
|
||||
public class ClientSession implements Runnable {
|
||||
|
||||
private String username;
|
||||
private final Socket socket;
|
||||
private final UserManager userManager;
|
||||
private ObjectInputStream in;
|
||||
private ObjectOutputStream out;
|
||||
|
||||
|
||||
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;
|
||||
try
|
||||
{
|
||||
out = new ObjectOutputStream(socket.getOutputStream());
|
||||
out.flush();
|
||||
in = new ObjectInputStream(socket.getInputStream());
|
||||
} catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
|
||||
// TODO: Welcome the user (login step)
|
||||
// Welcome the user (login step)
|
||||
// 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))
|
||||
{
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
ChatMessage loginMsg = (ChatMessage) obj;
|
||||
if (loginMsg.getType() != MessageType.LOGIN)
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", null, "Invalid login request"));
|
||||
out.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Extract the username.
|
||||
String requestedUser = loginMsg.getContent();
|
||||
|
||||
// 4. Try to register the user via userManager.addUser(...).
|
||||
boolean success = userManager.addUser(requestedUser, this);
|
||||
|
||||
// 5. If the username is taken, send back LOGIN_FAILED and close the socket.
|
||||
if (!success)
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_FAILED, "Server", null, "Username is already taken"));
|
||||
out.flush();
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...)
|
||||
// and send back LOGIN_SUCCESS.
|
||||
this.username = requestedUser;
|
||||
out.writeObject(new ChatMessage(MessageType.LOGIN_SUCCESS, "Server", null, "Welcome "+username));
|
||||
out.flush();
|
||||
System.out.println("User logged in: "+username);
|
||||
|
||||
// TODO: Main message loop
|
||||
// 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).
|
||||
while (true)
|
||||
{
|
||||
Object received = in.readObject();
|
||||
if (received instanceof ChatMessage)
|
||||
{
|
||||
handleChatMessage((ChatMessage) received);
|
||||
} else if (received instanceof FileMessage)
|
||||
{
|
||||
handleFileMessage((FileMessage) received);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Disconnected: " + username);
|
||||
} finally {
|
||||
// TODO: Remove the user from UserManager so they no longer
|
||||
// Remove the user from UserManager so they no longer
|
||||
// receive broadcasts or appear in users list
|
||||
if (username != null)
|
||||
{
|
||||
userManager.removeUser(username);
|
||||
System.out.println("User removed: "+username);
|
||||
}
|
||||
try
|
||||
{
|
||||
if (socket != null && !socket.isClosed())
|
||||
{
|
||||
socket.close();
|
||||
}
|
||||
} catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,13 +121,36 @@ public class ClientSession implements Runnable {
|
||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||
switch (msg.getType()) {
|
||||
case PUBLIC_MESSAGE -> {
|
||||
// TODO: Broadcast this message to every connected client.
|
||||
// Broadcast this message to every connected client.
|
||||
for (ClientSession session : userManager.getAllSessions())
|
||||
{
|
||||
if (session != this)
|
||||
{
|
||||
session.out.writeObject(msg);
|
||||
session.out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
case PRIVATE_MESSAGE -> {
|
||||
// TODO: Forward this message to the receiver user.
|
||||
// Forward this message to the receiver user.
|
||||
String receiver = msg.getReceiver();
|
||||
ClientSession target = userManager.getUser(receiver);
|
||||
if (target != null)
|
||||
{
|
||||
target.out.writeObject(msg);
|
||||
target.out.flush();
|
||||
} else {
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", null,
|
||||
"User " + receiver + " is not online."));
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
case USER_LIST -> {
|
||||
// TODO: Reply to the requester with the list of online users.
|
||||
// Reply to the requester with the list of online users.
|
||||
String list = userManager.listUsers();
|
||||
ChatMessage listMsg = new ChatMessage(MessageType.USER_LIST, "Server", null, list);
|
||||
out.writeObject(listMsg);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +163,16 @@ public class ClientSession implements Runnable {
|
||||
Files.write(sentPath, fileMsg.getData());
|
||||
Files.write(recvPath, fileMsg.getData());
|
||||
|
||||
// TODO: Forward the received file-message to the destination user.
|
||||
// Forward the received file-message to the destination user.
|
||||
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
|
||||
if (receiver != null)
|
||||
{
|
||||
receiver.out.writeObject(fileMsg);
|
||||
receiver.out.flush();
|
||||
} else
|
||||
{
|
||||
out.writeObject(new ChatMessage(MessageType.PRIVATE_MESSAGE, "Server", null, "Cannot send file; user "+fileMsg.getReceiver()+" is offline"));
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user