C#乱码问题

发送带中文的协议乱码

C# 默认编码格式为Unicode (UTF-16)
UTF-8 :一个中文占3三个字节 用什么发就用什么解(这个有点废话)

发送

public void AddString(string str)
		{
			//求传入长度
			Int32 length =  Encoding.UTF8.GetBytes(str).Length;
			byte[] length_bytes = BitConverter.GetBytes(length);
			byte[] contents = Encoding.UTF8.GetBytes(str);

			if (Bs_Content != null)
			{
				Bs_Content = Bs_Content.Concat(length_bytes).Concat(contents).ToArray();
			}
			else
			{
				Bs_Content = length_bytes.Concat(contents).ToArray();
			}
		}

解析

public string GetString(int start, ref int end)
		{
			if (Bs_Content == null)
			{
				return "";
			}
			if (Bs_Content.Length <start + sizeof(Int32))
			{
				return "";
			}
			Int32 length = BitConverter.ToInt32(Bs_Content, start);//取出长度
			if (Bs_Content.Length <start + sizeof(Int32) + length)
			{
				return "";
			}

			
			string str = Encoding.UTF8.GetString(Bs_Content, start+ sizeof(Int32), length);

			end = start + sizeof(Int32) + length;
			//string str = Encoding.UTF8.GetString(Bs_Content, start, length);
			return str;
		}

在这里插入图片描述

测试

public void MsgGetCreateRoleInfoList(Player player, ProtocolBase protobase)
		{
			Protocolbytes pbytes = new Protocolbytes();
			List<Role> roles = DataMgr.Instance.GetRoleListInfo();
			int count = roles.Count;
			//加协议名称
			pbytes.AddString("GetCreateRoleInfoList");
			//加内容
			pbytes.AddInt(count);
			for(int i = 0; i < count; ++i)
			{
				
				 pbytes.AddInt(roles[i].id);
				/*
				Console.WriteLine(roles[i].id);
				pbytes.AddInt(roles[i].LL);
				pbytes.AddInt(roles[i].MJ);
				pbytes.AddInt(roles[i].ZL);
				 */
				pbytes.AddString("中文啊啊AAA");
			}
			Test(pbytes);
			//player.Send(pbytes);
		}
		public void Test(ProtocolBase protocolBase)
		{
			int start = 0;
			Protocolbytes pbytes = (Protocolbytes)protocolBase;
			string PropName = pbytes.GetString(start,ref start);
			int count = pbytes.GetInt(start, ref start);
			for (int i = 0; i < count; i++)
			{
				int id = pbytes.GetInt(start,ref start);
				string Name = pbytes.GetString(start, ref start);
				Console.WriteLine("id:" + id);
				Console.WriteLine("Name:" + Name);

			}
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值