57 lines
2.5 KiB
C#
57 lines
2.5 KiB
C#
using Fantasy.Async;
|
||
using Fantasy.Entitas;
|
||
using Fantasy.Helper;
|
||
using Fantasy.Network;
|
||
using Fantasy.Network.Interface;
|
||
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
|
||
|
||
namespace Fantasy;
|
||
|
||
public sealed class C2G_LoginRequestHandler : MessageRPC<C2G_LoginRequest, G2C_LoginResponse>
|
||
{
|
||
protected override async FTask Run(Session session, C2G_LoginRequest request, G2C_LoginResponse response, Action reply)
|
||
{
|
||
var scene = session.Scene;
|
||
if (string.IsNullOrEmpty(request.Name))
|
||
{
|
||
// 返回的1代表的用户名为空。
|
||
response.ErrorCode = 1;
|
||
return;
|
||
}
|
||
Log.Debug($"登陆的用户名为:{request.Name}");
|
||
// 检查用户是否存在
|
||
Account account = null;
|
||
var worldDataBase = scene.World.DataBase;
|
||
// 用协程锁来处理,异步逻辑的原子问题。
|
||
using (await scene.CoroutineLockComponent.Wait(CoroutineLockConst.LoginKey, request.Name.GetHashCode()))
|
||
{
|
||
account = await worldDataBase.First<Account>(d => d.Name == request.Name, true);
|
||
// 如果用户不存在,则创建一个用户。并且保存到数据库中.
|
||
if (account == null)
|
||
{
|
||
account = Entity.Create<Account>(scene, true, true);
|
||
account.Name = request.Name;
|
||
account.CreateTime = TimeHelper.Now;
|
||
await worldDataBase.Save(account);
|
||
Log.Debug($"当前账号:{request.Name} 不存在,所以创建了一个新的账号。");
|
||
}
|
||
else
|
||
{
|
||
Log.Debug($"当前账号:{request.Name} 已经存在,直接登陆。");
|
||
}
|
||
}
|
||
// 跟Session关联上Account,下次发送消息,直接可以通过GateAccountFlagComponent来获取Account。
|
||
session.AddComponent<GateAccountFlagComponent>().Account = account;
|
||
// 登陆到其他服务器。
|
||
var result = await GateLoginHelper.Online(session, account);
|
||
if (result != 0)
|
||
{
|
||
response.ErrorCode = result;
|
||
Log.Error($"登陆到其他服务器失败,ErrorCode:{result}");
|
||
return;
|
||
}
|
||
Log.Debug($"登陆成功 Name:{account.Name}");
|
||
// 用这个方法来暂时消除async的黄色波浪线。这个只是为了消除黄色的波浪线,如果有await这个就可以不用。
|
||
// await FTask.CompletedTask;
|
||
}
|
||
} |