Skip to content

Commit

Permalink
WIP restructuring client side of websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
alyssaruth committed Oct 9, 2024
1 parent 9dcb189 commit 9a5043b
Show file tree
Hide file tree
Showing 16 changed files with 156 additions and 212 deletions.
9 changes: 5 additions & 4 deletions client/src/main/java/object/RoomTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import http.dto.RoomSummary;
import online.screen.EntropyLobby;
import online.screen.GameRoom;
import online.util.XmlBuilderClient;
Expand Down Expand Up @@ -125,7 +126,7 @@ private void setRenderersAndSorters()
setRowSorter(sorter);
}

public void synchroniseRooms(List<RoomWrapper> rooms)
public void synchroniseRooms(List<RoomSummary> rooms)
{
addNewRooms(rooms);
updateRooms(rooms);
Expand All @@ -134,12 +135,12 @@ public void synchroniseRooms(List<RoomWrapper> rooms)
getRowSorter().allRowsChanged();
}

private void addNewRooms(List<RoomWrapper> rooms)
private void addNewRooms(List<RoomSummary> rooms)
{
for (int i=0; i<rooms.size(); i++)
{
RoomWrapper room = rooms.get(i);
String name = room.getRoomName();
RoomSummary room = rooms.get(i);
String name = room.getName();

if (!modelContainsRoom(name))
{
Expand Down
30 changes: 13 additions & 17 deletions client/src/main/java/online/screen/EntropyLobby.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import http.dto.LobbyResponse;
import http.dto.RoomSummary;
import object.OnlineUsername;
import object.RoomTable;
import object.RoomWrapper;
Expand Down Expand Up @@ -62,7 +64,7 @@ public class EntropyLobby extends JFrame

//Declaring these as 'Map' to fix obscure Java8 bug
private Map<String, GameRoom> hmGameRoomByRoomName = new ConcurrentHashMap<>();
private Map<String, RoomWrapper> hmRoomByRoomName = new ConcurrentHashMap<>();
private Map<String, RoomSummary> hmRoomByRoomName = new ConcurrentHashMap<>();

private DefaultListModel<OnlineUsername> usernamesModel = new DefaultListModel<>();
private UsernameRenderer usernameRenderer = new UsernameRenderer();
Expand Down Expand Up @@ -227,7 +229,7 @@ public OnlineStatsPanel getOnlineStatsPanel()
return statsPanel;
}

public RoomWrapper getRoomForName(String roomName)
public RoomSummary getRoomForName(String roomName)
{
return hmRoomByRoomName.get(roomName);
}
Expand All @@ -237,7 +239,7 @@ public GameRoom getGameRoomForName(String roomName)
return hmGameRoomByRoomName.get(roomName);
}

public void addOrUpdateRoom(String roomName, RoomWrapper room)
public void addOrUpdateRoom(String roomName, RoomSummary room)
{
hmRoomByRoomName.put(roomName, room);
}
Expand All @@ -251,6 +253,14 @@ public GameRoom createGameRoom(RoomWrapper room)

return gameRoom;
}

public void syncLobby(LobbyResponse response)
{
SwingUtilities.invokeLater(() -> {
roomTable.synchroniseRooms(response.getRooms());
synchUsernames(response.getUsers());
});
}

public void synchroniseRooms(final List<RoomWrapper> rooms)
{
Expand Down Expand Up @@ -310,20 +320,6 @@ private void initChatPanelIfNecessary()
}
}

public void synchUsernamesInAwtThread(final List<OnlineUsername> usernamesFromServer)
{
Runnable usernameSynchRunnable = new Runnable()
{
@Override
public void run()
{
synchUsernames(usernamesFromServer);
}
};

SwingUtilities.invokeLater(usernameSynchRunnable);
}

private void synchUsernames(List<OnlineUsername> usernamesFromServer)
{
initChatPanelIfNecessary();
Expand Down
26 changes: 8 additions & 18 deletions client/src/main/java/online/util/ResponseHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,20 @@

public class ResponseHandler implements XmlConstants
{
public static void handleResponse(String messageStr, String responseStr) throws Throwable
{
EntropyLobby lobby = ScreenCache.getEntropyLobby();

SecretKey symmetricKeyForDecryption = MessageUtil.symmetricKey;
if (symmetricKeyForDecryption == null)
{
Debug.stackTrace("Handling server response with no symmetricKey set");
}

responseStr = EncryptionUtil.decrypt(responseStr, symmetricKeyForDecryption);
if (responseStr == null)
{
public static void handleResponse(String messageStr, String responseStr) throws Throwable {
var decryptedResponseStr = EncryptionUtil.decrypt(responseStr, MessageUtil.symmetricKey);
if (decryptedResponseStr == null) {
throw new Throwable("Failed to decrypt response. Server may not be genuine.");
}


handleDecryptedResponse(messageStr, responseStr);
}
public static void handleDecryptedResponse(String messageStr, String responseStr) throws Throwable {
Document response = XmlUtil.getDocumentFromXmlString(responseStr);

Element root = response.getDocumentElement();
String responseName = root.getNodeName();
EntropyLobby lobby = ScreenCache.getEntropyLobby();

if (responseName.equals(RESPONSE_TAG_KICK_OFF))
{
Expand All @@ -57,10 +51,6 @@ else if (responseName.equals(RESPONSE_TAG_CHAT_NOTIFICATION))
{
handleChatResponse(root, lobby);
}
else if (responseName.equals(RESPONSE_TAG_LOBBY_NOTIFICATION))
{
handleLobbyResponse(root, lobby);
}
else if (responseName.equals(RESPONSE_TAG_JOIN_ROOM_RESPONSE))
{
handleJoinRoomAck(root, lobby);
Expand Down
5 changes: 5 additions & 0 deletions client/src/main/java/util/ClientNotificationRunnable.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ public void run()
return;
}

response = EncryptionUtil.decrypt(response, MessageUtil.symmetricKey);
if (response == null) {
throw new Throwable("Failed to decrypt response. Server may not be genuine.");
}

if (ClientGlobals.INSTANCE.getWebSocketReceiver().canHandleMessage(response)) {
ClientGlobals.INSTANCE.getWebSocketReceiver().receiveMessage(response);
} else {
Expand Down
5 changes: 4 additions & 1 deletion client/src/main/kotlin/http/WebSocketReceiver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package http
import http.dto.ClientMessage
import http.dto.LobbyResponse
import kong.unirest.JsonObjectMapper
import screen.ScreenCache
import utils.CoreGlobals.logger

class WebSocketReceiver {
Expand Down Expand Up @@ -30,5 +31,7 @@ class WebSocketReceiver {
private fun deserializeClientMessage(rawMessage: String): ClientMessage =
jsonObjectMapper.readValue(rawMessage, ClientMessage::class.java)

private fun handleLobbyResponse(clientMessage: LobbyResponse) {}
private fun handleLobbyResponse(clientMessage: LobbyResponse) {
ScreenCache.getEntropyLobby().syncLobby(clientMessage)
}
}
1 change: 0 additions & 1 deletion core/src/main/java/util/XmlConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public interface XmlConstants
public static final String SOCKET_NAME_LOBBY = "Lobby" + SOCKET_NAME_SUFFIX;

//Server notifications
public static final String RESPONSE_TAG_LOBBY_NOTIFICATION = "LobbyNotification";
public static final String RESPONSE_TAG_CHAT_NOTIFICATION = "ChatNotification";
public static final String RESPONSE_TAG_PLAYER_NOTIFICATION = "PlayerNotification";
public static final String RESPONSE_TAG_BID_NOTIFICATION = "BidNotification";
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/kotlin/utils/CoreGlobals.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import ch.qos.logback.classic.Logger as LogbackLogger
import com.fasterxml.jackson.databind.ObjectMapper
import java.time.Clock
import logging.Logger
import org.slf4j.LoggerFactory
Expand All @@ -9,4 +10,5 @@ object CoreGlobals {
val slf4jLogger: LogbackLogger = LoggerFactory.getLogger("entropy") as LogbackLogger
@JvmField var logger: Logger = Logger(slf4jLogger)
var clock: Clock = Clock.systemUTC()
val objectMapper = ObjectMapper()
}
23 changes: 12 additions & 11 deletions server/src/main/java/object/Room.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public int addToCurrentPlayers(String username, int playerNumber)
observers.remove(username);

notifyAllPlayersOfPlayerChange(username, false);
server.lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
return playerNumber;
}
}
Expand Down Expand Up @@ -147,11 +147,11 @@ else if (playerSize == 0)

private void notifyAllPlayersOfPlayerChange(String userToExclude, boolean blocking)
{
Document notification = XmlBuilderServer.getPlayerNotification(this);
String notification = XmlBuilderServer.getPlayerNotification(this);
notifyAllUsersViaGameSocket(notification, userToExclude, blocking);
}

private void notifyAllUsersViaGameSocket(Document notification, String userToExclude, boolean blocking)
private void notifyAllUsersViaGameSocket(String notification, String userToExclude, boolean blocking)
{
HashSet<String> usersToNotify = getAllUsersInRoom();
if (userToExclude != null)
Expand Down Expand Up @@ -180,7 +180,7 @@ private void finishCurrentGame(int winningPlayer)
initialiseGame();

//Notify everyone that the game is over now we've finished setting up
Document notification = XmlBuilderServer.factoryGameOverNotification(this, winningPlayer);
String notification = XmlBuilderServer.factoryGameOverNotification(this, winningPlayer);
notifyAllUsersViaGameSocket(notification, null, false);
}

Expand All @@ -203,7 +203,7 @@ public void resetCurrentPlayers(boolean fireLobbyChanged)
hmFormerPlayerByPlayerNumber.clear();
if (fireLobbyChanged)
{
server.lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
}
}

Expand All @@ -218,15 +218,15 @@ public void addToObservers(String username)
}

removePlayer(username, false);
server.lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
}
}
public void removeFromObservers(String username)
{
boolean removed = observers.remove(username);
if (removed)
{
server.lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
}

clearChatIfEmpty();
Expand Down Expand Up @@ -342,7 +342,7 @@ public void setUpNextRound(int losingPlayerNumber)

currentGame.setRoundNumber(currentRoundNumber + 1);

Document newRoundNotification = XmlBuilderServer.factoryNewRoundNotification(this, nextRoundDetails, losingPlayerNumber);
String newRoundNotification = XmlBuilderServer.factoryNewRoundNotification(this, nextRoundDetails, losingPlayerNumber);
notifyAllUsersViaGameSocket(newRoundNotification, null, false);
}
}
Expand Down Expand Up @@ -414,8 +414,9 @@ private void saveStatistics(String winningPlayer, int roundNumber)

//Push out a stats notification
Document statsNotification = XmlBuilderServer.factoryStatisticsNotification(player);
String notificationString = XmlUtil.getStringFromDocument(statsNotification);
UserConnection usc = ServerGlobals.INSTANCE.getUscStore().findForName(player);
usc.sendNotificationInWorkerPool(statsNotification, server, XmlConstants.SOCKET_NAME_LOBBY, null);
usc.sendNotificationInWorkerPool(notificationString, server, XmlConstants.SOCKET_NAME_LOBBY, null);
}
}
}
Expand Down Expand Up @@ -527,7 +528,7 @@ public boolean addBidForPlayer(String gameId, int playerNumber, int roundNumber,
if (added)
{
//Notify all other players
Document bidNotification = XmlBuilderServer.getBidNotification(roomName, playerNumber, newBid);
String bidNotification = XmlBuilderServer.getBidNotification(roomName, playerNumber, newBid);
notifyAllUsersViaGameSocket(bidNotification, null, false);
}

Expand All @@ -543,7 +544,7 @@ public void addToChatHistoryAndNotifyUsers(OnlineMessage message)

chatHistory.add(message);

Document chatMessage = XmlBuilderServer.getChatNotification(roomName, message);
String chatMessage = XmlBuilderServer.getChatNotification(roomName, message);
HashSet<String> users = getAllUsersInRoom();
List<UserConnection> uscs = ServerGlobals.INSTANCE.getUscStore().getAllForNames(users);
server.sendViaNotificationSocket(uscs, chatMessage, XmlConstants.SOCKET_NAME_CHAT, false);
Expand Down
28 changes: 6 additions & 22 deletions server/src/main/java/server/EntropyServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public void removeFromUsersOnline(UserConnection usc) {
return;
}

lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
}

private void resetLobby() {
Expand Down Expand Up @@ -204,35 +204,19 @@ private void addToChatHistory(String name, OnlineMessage message) {
lobbyMessages.add(message);
List<UserConnection> usersToNotify = ServerGlobals.INSTANCE.getUscStore().getAll();

Document chatMessage = XmlBuilderServer.getChatNotification(name, message);
String chatMessage = XmlBuilderServer.getChatNotification(name, message);
sendViaNotificationSocket(usersToNotify, chatMessage, XmlConstants.SOCKET_NAME_CHAT);
} else {
Room room = hmRoomByName.get(name);
room.addToChatHistoryAndNotifyUsers(message);
}
}

public void lobbyChanged() {
lobbyChanged(null);
}

public void lobbyChanged(UserConnection userToExclude) {
List<UserConnection> usersToNotify = new ArrayList<>(ServerGlobals.INSTANCE.getUscStore().getAll());
if (userToExclude != null) {
usersToNotify.remove(userToExclude);
}

Document lobbyMessage = XmlUtil.factoryNewDocument();
XmlBuilderServer.appendLobbyResponse(lobbyMessage, this);

sendViaNotificationSocket(usersToNotify, lobbyMessage, XmlConstants.SOCKET_NAME_LOBBY);
}

private void sendViaNotificationSocket(List<UserConnection> uscs, Document message, String socketName) {
public void sendViaNotificationSocket(List<UserConnection> uscs, String message, String socketName) {
sendViaNotificationSocket(uscs, message, socketName, false);
}

public void sendViaNotificationSocket(List<UserConnection> uscs, Document message, String socketName, boolean blocking) {
public void sendViaNotificationSocket(List<UserConnection> uscs, String message, String socketName, boolean blocking) {
AtomicInteger counter = null;
if (blocking) {
int size = uscs.size();
Expand All @@ -242,7 +226,7 @@ public void sendViaNotificationSocket(List<UserConnection> uscs, Document messag
sendViaNotificationSocket(uscs, message, socketName, counter);
}

private void sendViaNotificationSocket(List<UserConnection> uscs, Document message, String socketName, AtomicInteger counter) {
private void sendViaNotificationSocket(List<UserConnection> uscs, String message, String socketName, AtomicInteger counter) {
int size = uscs.size();
for (int i = 0; i < size; i++) {
UserConnection usc = uscs.get(i);
Expand Down Expand Up @@ -326,7 +310,7 @@ public void registerCopy(Room room) {

if (newRoom != null) {
newRoom.setIsCopy(true);
lobbyChanged();
ServerGlobals.lobbyService.lobbyChanged();
}
}

Expand Down
Loading

0 comments on commit 9a5043b

Please sign in to comment.