Skip to content

Commit

Permalink
Fix: Incorrect user joining room logic
Browse files Browse the repository at this point in the history
  • Loading branch information
NuanRMxi committed Sep 8, 2024
1 parent 8b59e4e commit 568eeae
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 71 deletions.
39 changes: 34 additions & 5 deletions ConnectionMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,16 @@ public class GetData : Message
public class JoinServerFailed : Message
{
public new readonly string action = "joinServerFailed";
public string reason = "unknown";
public ReasonType reason = ReasonType.Unknown;

public enum ReasonType
{
AuthFailedByPwdIncorrect,// Will be kicked out
AuthFailedByPwdNull, // Will be kicked out
JoinFailedByIllegalClient,
JoinFailedByInvalidParameter,
Unknown
}
}

/// <summary>
Expand All @@ -50,7 +59,15 @@ public class JoinServerSuccess : Message
public class NewRoomFailed : Message
{
public new readonly string action = "newRoomFailed";
public string reason = "unknown";
public ReasonType reason = ReasonType.Unknown;
public enum ReasonType
{
RoomAlreadyExists,
RoomIdentifierInvalid,
RoomIdentifierTooLong,
AlreadyInRoom,
Unknown
}
}

/// <summary>
Expand All @@ -65,8 +82,15 @@ public class NewRoomSuccess : Message
/// </summary>
public class JoinRoomFailed : Message
{
public new readonly string action = "joinRoomFaild";
public string reason = "unknown";
public new readonly string action = "joinRoomFailed";
public ReasonType reason = ReasonType.Unknown;
public enum ReasonType
{
RoomNotFound,
RoomIsFull,
AlreadyInRoom,
Unknown
}
}
/// <summary>
/// Room join success message | 房间加入成功消息
Expand All @@ -81,7 +105,12 @@ public class JoinRoomSuccess : Message
public class LeaveRoomFailed : Message
{
public new readonly string action = "leaveRoomFailed";
public string reason = "unknown";
public ReasonType reason = ReasonType.Unknown;
public enum ReasonType
{
NotInRoom,
Unknown
}
}
/// <summary>
/// Leave room success message | 离开房间成功消息
Expand Down
53 changes: 18 additions & 35 deletions GameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public static void RemoveUser(IWebSocketConnection socket)
{
if(userList[i].userSocket == socket)
{
if (userList[i].userRoom != null)
if (userList[i].room != null)
{
userList[i].userRoom!.Leave(userList[i]);
userList[i].room!.Leave(userList[i]);
}
userList.RemoveAt(i);
}
Expand Down Expand Up @@ -129,10 +129,10 @@ public Room(User owner, string roomID)
throw new ArgumentException("RoomIdentifier can only use English or numbers.");// 房间ID只能使用英文或数字
}
this.owner = owner;
owner.userRoom = this;
owner.room = this;
this.roomID = roomID;
userList = new();
LogManager.WriteLog($"New room created: {roomID} by {owner.userName}");
LogManager.WriteLog($"New room created: {roomID} by {owner.name}");
}
/// <summary>
/// User join room | 用户加入房间
Expand All @@ -141,7 +141,7 @@ public Room(User owner, string roomID)
public void Join(User user)
{
userList.Add(user);
user.userRoom = this;
user.room = this;
}
/// <summary>
/// User leave room | 用户离开房间
Expand Down Expand Up @@ -193,9 +193,8 @@ public class User
{
public enum Status
{
Disconnect = 0,
AFK = 1,
InRoom = 2
AFK,
InRoom
}

/// <summary>
Expand All @@ -211,9 +210,9 @@ public class UserConfig

public Status userStatus = Status.AFK;
public UserConfig? userConfig;
public string userName;
public string name;
public IWebSocketConnection userSocket;
public Room? userRoom;
public Room? room;
public DateTime joinTime = DateTime.Now;
public string avatarUrl = Program.config.userDefauletAvatarUrl;

Expand All @@ -222,29 +221,17 @@ public User(string name, IWebSocketConnection socket, UserConfig config)
{
if(name == null)
{
userName = "anonymous";
this.name = "anonymous";
}
else
{
userName = name;
this.name = name;
}
userSocket = socket;
userConfig = config;
}

public void JoinRoom(Room room)
{
room.Join(this);
userRoom = room;
userStatus = Status.InRoom;
}

public void LeaveRoom()
{
userRoom!.Leave(this);
userRoom = null;
userStatus = Status.AFK;
}


/// <summary>
/// New Room | 创建房间
Expand All @@ -262,28 +249,24 @@ public void CreateRoom(string roomID)
RoomManager.AddRoom(this, roomID);
}
}

public void Remove()
{
Disconnect();
}

/// <summary>
/// User disconnect | 用户断开连接
/// </summary>
public void Disconnect()
{
UserManager.RemoveUser(userSocket);
if (userRoom != null)
if (room != null)
{
if (userRoom.owner == this)
if (room.owner == this)
{
if (userRoom.Count == 0)
if (room.Count == 0)
{
RoomManager.RemoveRoom(userRoom);// Remove room | 移除房间
RoomManager.RemoveRoom(room);// Remove room | 移除房间
}
else
{
userRoom.owner = userRoom[0];
room.owner = room[0];
}
}
}
Expand Down
91 changes: 60 additions & 31 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,16 @@ private static void Main(string[] args)
LogManager.WriteLog("User List:");
foreach (var user in GameManager.UserManager.userList)
{
LogManager.WriteLog($"{user.userName} Joined at {user.joinTime.ToString("yyyy-mm-dd hh:mm:ss")}");
LogManager.WriteLog(
$"{user.name} Joined at {user.joinTime.ToString("yyyy-mm-dd hh:mm:ss")} {user.room?.roomID ?? "No Room"}");
}
}
else if (command == "roomlist")
{
LogManager.WriteLog("Room List:");
foreach (var room in GameManager.RoomManager.roomList)
{
LogManager.WriteLog($"{room.roomID} Owner: {room.owner.userName}");
LogManager.WriteLog($"{room.roomID} Owner: {room.owner.name}");
}
}
}
Expand Down Expand Up @@ -183,11 +184,11 @@ private static async Task ServerOnMessage(string message, IWebSocketConnection s
LogManager.WriteLog("illegal client, Drop it.", LogManager.LogLevel.Warning);
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinServerFailed
{
reason =
"The client is already connected to the server.\nYour connection will be closed." //客户端已经连接服务器,您的连接将被关闭。
reason = ConnectionMessage.Server.JoinServerFailed.ReasonType
.JoinFailedByIllegalClient //客户端已经连接服务器,您的连接将被关闭。
}));
LogManager.WriteLog(
$"There are illegal clients attempting to pass metadata multiple times: {GameManager.UserManager.GetUser(socket).userName}");
$"There are illegal clients attempting to pass metadata multiple times: {GameManager.UserManager.GetUser(socket).name}");
GameManager.UserManager.RemoveUser(socket);
socket.Close();
return;
Expand All @@ -198,11 +199,25 @@ await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinS
{
if (string.IsNullOrEmpty(data.password) || data.password != config.Password)
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinServerFailed
if (string.IsNullOrEmpty(data.password))
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinServerFailed
{
reason =
ConnectionMessage.Server.JoinServerFailed.ReasonType
.AuthFailedByPwdNull //服务器是私有的,但提供的密码为空。您的连接将被关闭。
}));
}
else
{
reason =
"The server is private, but no password was provided or the password is invalid.\nYour connection will be closed." //服务器是私有的,但没有提供密码或密码无效。您的连接将被关闭。
}));
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinServerFailed
{
reason =
ConnectionMessage.Server.JoinServerFailed.ReasonType
.AuthFailedByPwdIncorrect //服务器是私有的,但提供的密码无效。您的连接将被关闭。
}));
}

LogManager.WriteLog(
$"The client attempted to connect to the server, but authentication failed: {data.userName}");
//Authentication failed, Drop and disconnect | 认证失败,丢弃并断开连接
Expand All @@ -215,6 +230,18 @@ await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinS
// Add user | 添加用户
LogManager.WriteLog($"User {clientMetaData.data.userName} connected.");
LogManager.WriteLog($"Raw Message: {message}", LogManager.LogLevel.Debug);
//Check all parameters | 检查所有参数
if (string.IsNullOrEmpty(clientMetaData.data.userName) || data.isDebugger == null ||

Check warning on line 234 in Program.cs

View workflow job for this annotation

GitHub Actions / build-linux

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'

Check warning on line 234 in Program.cs

View workflow job for this annotation

GitHub Actions / build-windows

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'
data.isSpectator == null || data.features == null)

Check warning on line 235 in Program.cs

View workflow job for this annotation

GitHub Actions / build-linux

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'

Check warning on line 235 in Program.cs

View workflow job for this annotation

GitHub Actions / build-windows

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinServerFailed
{
reason = ConnectionMessage.Server.JoinServerFailed.ReasonType
.JoinFailedByInvalidParameter //非法参数,请检查后重试。
}));
return;
}

GameManager.UserManager.AddUser(clientMetaData.data.userName, socket, new GameManager.User.UserConfig
{
isAnonymous = data.userName == null,
Expand Down Expand Up @@ -245,9 +272,9 @@ await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinS
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.NewRoomFailed
{
reason = "You are already in a room." // 你已经在房间里了。
reason = ConnectionMessage.Server.NewRoomFailed.ReasonType.AlreadyInRoom // 你已经在房间里了。
}));
LogManager.WriteLog($"User {user.userName} tried to create a room while in a room."); // 用户尝试在房间里创建房间。
LogManager.WriteLog($"User {user.name} tried to create a room while in a room."); // 用户尝试在房间里创建房间。
return;
}

Expand All @@ -256,16 +283,17 @@ await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.NewRo
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.NewRoomFailed
{
reason = "The room already exists." // 房间已存在。
reason = ConnectionMessage.Server.NewRoomFailed.ReasonType.RoomAlreadyExists // 房间已存在。
}));
LogManager.WriteLog(
$"User {user.userName} tried to create a room with the same name."); // 用户尝试使用相同的名称创建房间。
$"User {user.name} tried to create a room with the same name."); // 用户尝试使用相同的名称创建房间。
return;
}


GameManager.UserManager.GetUser(socket).CreateRoom(newRoom.data.roomID);
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.NewRoomSuccess()));
LogManager.WriteLog($"User {user.userName} has created a new room {user.userRoom!.roomID}.");
LogManager.WriteLog($"User {user.name} has created a new room {user.room!.roomID}.");
}

if (msg.action == "joinRoom")
Expand All @@ -278,48 +306,49 @@ await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.NewRo
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinRoomFailed
{
reason = "You are already in a room." // 你已经在房间里了。
reason = ConnectionMessage.Server.JoinRoomFailed.ReasonType.AlreadyInRoom // 你已经在房间里了。
}));
LogManager.WriteLog($"User {user.userName} tried to join a room while in a room."); // 用户尝试在房间里加入房间。
LogManager.WriteLog($"User {user.name} tried to join a room while in a room."); // 用户尝试在房间里加入房间。
return;
}

//Find the room | 查找房间
var room = GameManager.RoomManager.GetRoom(joinRoom.data.roomID);
if (room != null)
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinRoomFailed
{
reason = "You are already in a room." // 你已经在房间里了。
}));
LogManager.WriteLog($"User {user.userName} tried to join a room while in a room."); // 用户尝试在房间里加入房间。
room.Join(user);
LogManager.WriteLog($"User {user.name} has joined the {room.roomID} room.");
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinRoomSuccess()));
}
else
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.JoinRoomFailed
{
reason = "The room does not exist." // 房间不存在。
reason = ConnectionMessage.Server.JoinRoomFailed.ReasonType.RoomNotFound // 房间不存在。
}));
LogManager.WriteLog($"User {user.userName} tried to join a room that does not exist.");// 用户尝试加入不存在的房间。
LogManager.WriteLog($"User {user.name} tried to join a room that does not exist."); // 用户尝试加入不存在的房间。
return;
}


}

if (msg.action == "leaveRoom")
{
var user = GameManager.UserManager.GetUser(socket);
if (user.userStatus == GameManager.User.Status.InRoom)
{
user.LeaveRoom();
LogManager.WriteLog($"User {user.userName} has left the {user.userRoom!.roomID} room.");
user.room!.Leave(user);
LogManager.WriteLog($"User {user.name} has left the {user.room!.roomID} room.");
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.LeaveRoomSuccess()));
}
else
{
await socket.Send(JsonConvert.SerializeObject(new ConnectionMessage.Server.LeaveRoomFailed
{
reason = "You are not in a room." // 你不在房间里。
reason = ConnectionMessage.Server.LeaveRoomFailed.ReasonType.NotInRoom // 你不在房间里。
}));
LogManager.WriteLog($"User {user.userName} tried to leave a room while not in a room.");// 用户尝试离开房间,但未在房间里。
LogManager.WriteLog($"User {user.name} tried to leave a room while not in a room."); // 用户尝试离开房间,但未在房间里。
}
}
}
Expand All @@ -342,18 +371,18 @@ private static async Task ServerOnError(Exception e, IWebSocketConnection socket
LogManager.WriteLog(e.Message, LogManager.LogLevel.Debug);
//WriteLog, Socket has been drop | 输出日志,连接被丢弃
LogManager.WriteLog("Socket has been drop, because of an error: " + e.Message, LogManager.LogLevel.Debug);
LogManager.WriteLog($"User {GameManager.UserManager.GetUser(socket).userName} unexpectedly disconnected",
LogManager.WriteLog($"User {GameManager.UserManager.GetUser(socket).name} unexpectedly disconnected",
LogManager.LogLevel.Warning);

//Drop and disconnect | 丢弃并断开连接
GameManager.UserManager.RemoveUser(socket);
GameManager.UserManager.GetUser(socket).Disconnect();
socket.Close();
}

private static async Task ServerOnClose(IWebSocketConnection socket)
{
LogManager.WriteLog($"user{GameManager.UserManager.GetUser(socket).userName} disconnected.");
GameManager.UserManager.RemoveUser(socket);
LogManager.WriteLog($"user{GameManager.UserManager.GetUser(socket).name} disconnected.");
GameManager.UserManager.GetUser(socket).Disconnect();
}

/// <summary>
Expand Down

0 comments on commit 568eeae

Please sign in to comment.