I work on unity game with peer-to-peer multiplayer using custom networking solution. When user connecting a receive event with its clientId and some payload in encoded json format. I want you to write code for SessionManager c# class, that will handle this event, perform validation of payload and manage dictionary of users, where clientId will be key and UserData struct will be value. It should validate that this user connection is not duplicated, generating unique id for each user and put it in UserData struct. Also, it should provide an API to manage connected users, granting access to users using clientId, or unique id generated by this service. Please make that code to be modular, coherent, validators and serializers should be separated and injected through constructor injection
Assistant
User
Please make changes to this code, assuming that clientId can change through recconections or duplicated connections from single user
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's an example implementation of the SessionManager class:
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SessionManager
{
private readonly Dictionary<string, UserData> _connectedUsers = new Dictionary<string, UserData>();
private readonly ISerializer _serializer;
private readonly IValidator _validator;
public SessionManager(ISerializer serializer, IValidator validator)
{
_serializer = serializer;
_validator = validator;
}
public void HandleUserConnected(string clientId, string payload)
{
if (!_validator.IsValidPayload(payload))
{
Debug.LogError("Invalid payload received from client.");
return;
}
var userData = _serializer.Deserialize<UserData>(payload);
if (userData == null)
{
Debug.LogError("Failed to deserialize user data.");
return;
}
if (_connectedUsers.ContainsKey(clientId))
{
Debug.LogWarning("Client is already connected.");
return;
}
userData.UserId = Guid.NewGuid().ToString();
_connectedUsers.Add(clientId, userData);
Debug.Log($"User connected: {userData.UserId}");
}
public UserData GetUser(string clientId)
{
if (_connectedUsers.ContainsKey(clientId))
{
return _connectedUsers[clientId];
}
return null;
}
public UserData GetUser(string userId)
{
return _connectedUsers.Values.FirstOrDefault(user => user.UserId == userId);
}
public void RemoveUser(string clientId)
{
if (_connectedUsers.ContainsKey(clientId))
{
_connectedUsers.Remove(clientId);
Debug.Log("User disconnected.");
}
}
}
public class UserData
{
public string UserId { get; set; }
// Add other user data properties here
}
public interface ISerializer
{
T Deserialize<T>(string payload);
string Serialize<T>(T data);
}
public interface IValidator
{
bool IsValidPayload(string payload);
}
In this implementation, the SessionManager class is responsible for managing the dictionary of connected users. The HandleUserConnected method is called when a user connects, and it validates the payload and adds the user to the dictionary with a unique id generated by the system. The GetUser method is used to retrieve a user's data by their clientId or userId. The RemoveUser method is used to remove a user from the dictionary when they disconnect.
The ISerializer and IValidator interfaces are used to separate the serialization and validation logic from the SessionManager class. This allows for flexibility in choosing different serialization and validation libraries or implementing custom logic.
Note that this is just one possible implementation, and there are many ways to approach this problem. The specific implementation details may vary depending on the requirements of your project.
To make the code more maintainable and reusable as a package, we can refactor it by introducing a few changes:
Encapsulate the user management logic in a separate class, UserManager, which will handle adding, retrieving, and removing users.
Use a ConcurrentDictionary to ensure thread safety when accessing the user data.
Implement an IUserManager interface to abstract the user management operations.
Provide a way to inject dependencies such as ISerializer and IValidator.
Here's the refactored code:
csharp
// UserManager.cs
using System.Collections.Concurrent;
using System.Linq;
using UnityEngine;
public class UserManager : IUserManager
{
private readonly ConcurrentDictionary<string, UserData> _connectedUsers = new ConcurrentDictionary<string, UserData>();
private readonly ISerializer _serializer;
private readonly IValidator _validator;
public UserManager(ISerializer serializer, IValidator validator)
{
_serializer = serializer;
_validator = validator;
}
public void HandleUserConnected(string clientId, string payload)
{
if (!_validator.IsValidPayload(payload))
{
Debug.LogError("Invalid payload received from client.");
return;
}
var userData = _serializer.Deserialize<UserData>(payload);
if (userData == null)
{
Debug.LogError("Failed to deserialize user data.");
return;
}
userData.UserId = Guid.NewGuid().ToString();
_connectedUsers.TryAdd(clientId, userData);
Debug.Log($"User connected: {userData.UserId}");
}
public UserData GetUser(string clientId)
{
return _connectedUsers.GetOrAdd(clientId, _ => new UserData());
}
public UserData GetUser(string userId)
{
return _connectedUsers.Values.FirstOrDefault(user => user.UserId == userId);
}
public void RemoveUser(string clientId)
{
_connectedUsers.TryRemove(clientId, out _);
Debug.Log("User disconnected.");
}
}
public interface IUserManager
{
void HandleUserConnected(string clientId, string payload);
UserData GetUser(string clientId);
UserData GetUser(string userId);
void RemoveUser(string clientId);
}
// UserData.cs
public class UserData
{
public string UserId { get; set; }
// Add other user data properties here
}
// ISerializer.cs
public interface ISerializer
{
T Deserialize<T>(string payload);
string Serialize<T>(T data);
}
// IValidator.cs
public interface IValidator
{
bool IsValidPayload(string payload);
}
Now, the SessionManager class can be simplified to use the UserManager class:
csharp
// SessionManager.cs
using System.Linq;
using UnityEngine;
public class SessionManager
{
private readonly IUserManager _userManager;
private readonly ISerializer _serializer;
private readonly IValidator _validator;
public SessionManager(IUserManager userManager, ISerializer serializer, IValidator validator)
{
_userManager = userManager;
_serializer = serializer;
_validator = validator;
}
public void HandleUserConnected(string clientId, string payload)
{
_userManager.HandleUserConnected(clientId, payload);
}
public UserData GetUser(string clientId)
{
return _userManager.GetUser(clientId);
}
public UserData GetUser(string userId)
{
return _userManager.GetUser(userId);
}
public void RemoveUser(string clientId)
{
_userManager.RemoveUser(clientId);
}
}
With these changes, the UserManager class is now responsible for managing the user data, and the SessionManager class delegates user management tasks to the UserManager. This separation of concerns makes the code more maintainable and reusable as a package.
To use this code as a package, you can create a Unity package by following the Unity Package Manager documentation: https://docs.unity3d.com/Manual/CustomPackages.html. This will allow you to easily distribute and reuse the code in different projects.