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;
		}

C#乱码问题_第1张图片

测试

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);

			}
		}

你可能感兴趣的:(C#乱码问题)