Unity-网络编程 笔记4

优化 笔记3 中服务端的业务的处理以及账号的管理

https://blog.csdn.net/shumake/article/details/136371619?spm=1001.2014.3001.5502

修改PlayerData.cs 删除PlayerInfo.cs, OnlinePlayer.cs

PlayerData.cs 账号管理

using Service.Modules;
using Service.Net;
using System.Collections.Generic;

namespace Service.Player
{
    internal class PlayerData
    {
        public static PlayerData Instance;
        //存储账号信息
        Dictionary<string, Module.RegisterMsgS2C> userMsg = new Dictionary<string, Module.RegisterMsgS2C>();
        public PlayerData() 
        {
            Instance = this;
        }
        //注册账号
        public Module.RegisterMsgS2C Add(Module.RegisterMsgC2S msg)
        {
            var item = new Module.RegisterMsgS2C();
            userMsg[msg.username] = item;
            item.username = msg.username;
            item.email = msg.email;
            item.password = msg.password;
            item.result = 0;
            return item;
        }
        //查询账号是否存在
        public bool Contain(string username)
        {
            return userMsg.ContainsKey(username);
        }
        //获取账号信息
        public Module.RegisterMsgS2C GetUser(string username)
        {
            return userMsg[username];
        }
        //获取所有账号信息
        public Dictionary<string, Module.RegisterMsgS2C> GetAllPlayers()
        {
            return userMsg;
        }
        //---------------------------------------------------------------------------------------------------------------
        //存储当前在线的玩家
        Dictionary<string, Client> LoginUser = new Dictionary<string, Client>();
        
        //当前账号是否在线
        public bool ContainLogin(string username)
        {
            return LoginUser.ContainsKey(username);
        }
        //添加在线
        public void AddLoginUser(string username,Client client)
        {
            LoginUser[username] = client;
        }
        //获取登录客户端
        public Client GetLoginUser(string username)
        {
            return LoginUser[username];
        }
        //移除在线
        public void LogoutUser(string username)
        {
            LoginUser.Remove(username);
        }
        //获取所有在线玩家
        public Dictionary<string, Client> GetAllLoginUser()
        {
            return LoginUser;
        }
    }
}

修改MsgManager.cs,删除回调函数

using Service.Helper;
using Service.Net;
using System;
using System.Text;

namespace Service.Manager
{
    internal class MsgManager
    {
        int msgLength = 0;//消息长度
        byte[] data = new byte[4096];//消息缓存区
        Client client;
        public MsgManager(Client _client) 
        {
            client = _client;
        }

        /// <summary>
        /// 处理数据粘包的问题
        /// </summary>
        /// <param name="length">该条消息的长度</param>
        /// <param name="buffer">该条消息的内容数据</param>
        public void MsgHandler(int length , byte[] buffer)
        {
            //length:当前消息的长度,msgLength上一个消息的长度
            Array.Copy(buffer, 0, data, msgLength, length);
            msgLength += length;

            //制定消息规则
            //包体大小(4),协议ID(4),包体
            //   大小    ID        包体内容
            // | ---- | ---- |-----------------------
            if (msgLength >= 8)
            {
                //获取包体大小
                byte[] _size = new byte[4];
                Array.Copy(data, 0, _size, 0, 4);
                int size = BitConverter.ToInt32(_size, 0);
                //获取该条消息的长度
                var _length = 8 + size;

                if (msgLength >= _length)
                {
                    //获取包体ID
                    byte[] _id = new byte[4];
                    Array.Copy(data, 4, _id, 0, 4);
                    int id = BitConverter.ToInt32(_id, 0);

                    //获取包体
                    byte[] body = new byte[size];
                    Array.Copy(data, 8, body, 0, size);

                    //发生的粘包行为
                    //msgLength == _length:该条消息是一条完整的消息
                    //msgLength > _length:该条消息有多条消息组合
                    if (msgLength > _length)
                    {
                        //将已处理的包体数据从data中移除
                        for (int i = 0; i < msgLength - _length; i++)
                        {
                            data[i] = data[_length + i];
                        }
                    }

                    msgLength -= _length;
                    Console.WriteLine($"收到客户端请求包体大小:{size}--------收到客户端请求:{id}--------收到客户端数据:{Encoding.UTF8.GetString(body)}");

                    //byte[] send_buffer = MsgHelper.MsgEncoding(10000, "Service:1234567890");
                    //client.Send(send_buffer);

                    switch (id)
                    {
                        case 1001://注册请求
                            MsgHelper.RegisterMsgHandler(body, client);
                            break;
                        case 1002://登录业务
                            MsgHelper.LoginMsgHandler(body, client);
                            break;
                        case 1003://聊天请求
                            MsgHelper.ChatMsgHandler(body);
                            break;
                        case 1004://退出请求
                            MsgHelper.LogoutMsgHandler(body, client);
                            break;
                        default:
                            client.SendToService(10000,"服务端还没有该业务!!!");
                            break;
                    }
                }
            }
        }
    }
}

 修改MsgHelper.cs业务处理逻辑中的参数

        /// <summary>
        /// 处理注册业务
        /// </summary>
        /// <param name="data"></param>
        /// <param name="Client"></param>
        public static void RegisterMsgHandler(byte[] data, Client client)
        {
            var msg = JsonHelper.ToObject<Module.RegisterMsgC2S>(data);
            Module.RegisterMsgS2C response = new Module.RegisterMsgS2C();
            if (PlayerData.Instance.Contain(msg.username))
            {
                //账号已存在,注册失败
                response.result = 1;
                MsgHelper.SendRegisterMsg(client, response);
                return;
            }
            else
            {
                response = PlayerData.Instance.Add(msg);
            }
            //发送注册成功消息
            MsgHelper.SendRegisterMsg(client, response);
        }
        /// <summary>
        /// 处理登录业务
        /// </summary>
        /// <param name="data"></param>
        /// <param name="Client"></param>
        public static void LoginMsgHandler(byte[] data, Client client)
        {
            var msg = JsonHelper.ToObject<Module.LoginMsgC2S>(data);
            Module.LoginMsgS2C response = new Module.LoginMsgS2C();
            if (PlayerData.Instance.Contain(msg.username))
            {
                //账号存在,判断密码
                if (msg.password == PlayerData.Instance.GetUser(msg.username).password)
                {
                    //判断账号是否有账号已登录
                    if (PlayerData.Instance.ContainLogin(msg.username))
                    {
                        Module.LogoutMsgS2C responseLogout = new Module.LogoutMsgS2C();
                        responseLogout.type = 1;
                        MsgHelper.SendLogoutMsg(PlayerData.Instance.GetLoginUser(msg.username), responseLogout);
                        PlayerData.Instance.LogoutUser(msg.username);
                    }

                    PlayerData.Instance.AddLoginUser(msg.username, client);
                    response.username = msg.username;
                    response.password = msg.password;
                    response.result = 0;
                    client.name = msg.username;
                    MsgHelper.SendLoginMsg(client, response);
                }
                else
                {
                    //密码错误,发送登录失败消息
                    response.result = 1;
                    MsgHelper.SendLoginMsg(client, response);
                }
                return;
            }
            else
            {
                //账号不存在
                response.result = 1;
                MsgHelper.SendLoginMsg(client, response);
            }
        }

        /// <summary>
        /// 处理退出业务
        /// </summary>
        /// <param name="data"></param>
        /// <param name="Client"></param>
        public static void LogoutMsgHandler(byte[] data, Client client)
        {
            var msg = JsonHelper.ToObject<Module.LogoutMsgC2S>(data);

            if (PlayerData.Instance.ContainLogin(msg.username))
            {
                //移除在线
                PlayerData.Instance.LogoutUser(msg.username);

                Module.LogoutMsgS2C response = new Module.LogoutMsgS2C();
                response.type = 0;
                //发送下线
                MsgHelper.SendLogoutMsg(client, response);
                return;
            }
        }

修改发送逻辑

/// <summary>
/// 发送注册结果消息
/// </summary>
/// <param name="client"></param>
/// <param name="registerObj"></param>
public static void SendRegisterMsg(Client client, Module.RegisterMsgS2C registerObj)
{
    //将json对象序列化
    string json = JsonHelper.ToJson(registerObj);

    client.SendToService(1001, json);
}
public static void SendLoginMsg(Client client, Module.LoginMsgS2C msg)
{
    string json = JsonHelper.ToJson(msg);
    client.SendToService(1002, json);
}

public static void SendLogoutMsg(Client client, Module.LogoutMsgS2C msg)
{
     string json = JsonHelper.ToJson(msg);
     client.SendToService(1004, json);
}

修改Client.cs

//存放当前客户端登录的账号
public string name;

//客户端异常时触发的方法
public void Remove()
{
    //移除客户端
    ClientManager.Instance.Clients.Remove(this);
    //移除在线
    PlayerData.Instance.LogoutUser(name);
    //关闭客户端监听
    client.Close();
}

当前项目源码

链接:https://pan.baidu.com/s/1tn13OCTywwng_u63ElZT9w?pwd=ddb4 
提取码:ddb4 

  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shumake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值