添加玩家行为协议,演示MongoDB的基本使用。

MsgPlayerAction协议

在SimpleServer工程内的Proto文件夹中添加UserMsg文件,同样地,在客户端的Scripts——Net——Proto文件夹内也添加这个文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using ProtoBuf;
using SimpleServer.Business;
[ProtoContract()]
public class MsgPlayerAction : MsgBase
{
public MsgPlayerAction()
{
ProtoType = ProtocolEnum.MsgPlayerAction;
}
[ProtoMember(1)]
public override ProtocolEnum ProtoType { get; set; }
[ProtoMember(2)]
public string? Key { get; set; }//行为类型
[ProtoMember(3)]
public string? Data { get; set; }//行为的具体数据
[ProtoMember(4)]
public BaseResult Result { get; set; }
}

这里的行为数据是string类型,可以根据需要声明为byte数组

修改ProtocolEnum,添加PlayerAction协议枚举,在客户端也添加

1
2
3
4
5
6
7
8
public enum ProtocolEnum
{
//...

MsgPlayerAction = 300,//玩家行为协议

MsgTest = 9999
}

修改Budiness文件夹内的ServerEnum,添加基本返回类型的枚举,在客户端也添加

1
2
3
4
5
6
7
8
9
namespace SimpleServer.Business
{
public enum BaseResult
{
Success,
Failure
}
//...
}

服务器记录PlayerAction

修改服务器的MsgHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/// <summary>
/// 分发角色行为
/// </summary>
public static void MsgPlayerAction(ClientSocket client,MsgBase msg)
{
if(msg == null)
{
Debug.LogError(client.Socket?.RemoteEndPoint?.ToString() + "MsgPlayerAction协议接收错误!");
}
else
{
User user = UserManager.Instance.GetUserById(client.UserId);
MsgPlayerAction msgPlayerAction = (MsgPlayerAction)msg;
bool isSuccess = MongoDBMgr.Instance.AddAction(client.UserId, user.Username, msgPlayerAction.Key, msgPlayerAction.Data);
msgPlayerAction.Key = null;
msgPlayerAction.Data = null;
msgPlayerAction.Result = isSuccess == true ? BaseResult.Success : BaseResult.Failure;
ServerSocket.Send(client, msgPlayerAction);
}

}

客户端发送PlayerAction

修改客户端的ProtocolManager

1
2
3
4
5
6
7
public static void PlayerActionRequest(string key, string data)
{
MsgPlayerAction msg = new MsgPlayerAction();
msg.Key = key;
msg.Data = data;
NetManager.Instance.SendMessage(msg);
}

测试

修改客户端的NetTest

1
2
3
4
5
6
7
8
void Update()
{
//...
if (Input.GetKeyDown(KeyCode.D))
{
ProtocolManager.PlayerActionRequest("StartGame", "ChangeName:xxx|Time:sss");
}
}

打开数据库,打开服务器,再打开客户端。

在客户端先按“A”键登录,登录成功后,按“D”键插入角色行为。

打开MongoDBCompass软件,然后打开默认的链接,就能看到自己刚刚插入的数据。