Unity3D Socket流数据大小端读写封装

博客介绍了在Unity3D中使用C#处理网络数据时,由于网络数据通常采用大端模式,而C#默认使用小端模式,因此需要进行大小端转换。作者分享了一段经过实践测试的C#代码,用于封装Socket的流数据读写,确保数据正确转换。
摘要由CSDN通过智能技术生成

网络数据是大端模式,而c#中的数据小端结构,那么在读写网络数据的时候需要进行转换。c#类库IPAddress已经封装了大小端的转换。

封装代码如下:


using System.IO; 
using System.Net;
using System;

namespace Framework
{
	public class NetStream
	{
		private MemoryStream stream;
		private BinaryReader reader;
		private BinaryWriter writer;

		public NetStream(byte[] buffer = null)
		{
			if (buffer == null)
			{
				this.stream = new MemoryStream();
			}
			else
			{
				this.stream = new MemoryStream(buffer);
			}

			this.reader = new BinaryReader(this.stream);
			this.writer = new BinaryWriter(this.stream);
		}

		public void Close()
		{
			this.stream.Close();
			this.reader.Close();
			this.writer.Close();
		}

		public long ReadInt64()
		{
			return IPAddress.HostToNetworkOrder(this.reader.ReadInt64());
		}

		public int ReadInt32() 
		{
			return IPAddress.HostToNetworkOrder(this.reader.ReadInt32());
		}

		public int ReadInt16(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值