最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用Protocol Buffer(ProtoBuf)進(jìn)行Unity中的Socket通信

 更新時(shí)間:2016年04月21日 14:48:34   作者:靈犀的博客  
這篇文章主要介紹了C#使用Protocol Buffer(ProtoBuf)進(jìn)行Unity的Socket通信的實(shí)例,Protocol Buffer是Google開發(fā)的數(shù)據(jù)格式,也是除了XML和JSON之外人氣第三高的^^需要的朋友可以參考下

首先來說一下本文中例子所要實(shí)現(xiàn)的功能:

  • 基于ProtoBuf序列化對(duì)象
  • 使用Socket實(shí)現(xiàn)時(shí)時(shí)通信
  • 數(shù)據(jù)包的編碼和解碼

下面來看具體的步驟:

一、Unity中使用ProtoBuf

導(dǎo)入DLL到Unity中,
創(chuàng)建網(wǎng)絡(luò)傳輸?shù)哪P皖悾?/p>

using System;
using ProtoBuf;

//添加特性,表示可以被ProtoBuf工具序列化
[ProtoContract]
public class NetModel {
 //添加特性,表示該字段可以被序列化,1可以理解為下標(biāo)
 [ProtoMember(1)] 
 public int ID;
 [ProtoMember(2)]
 public string Commit;
 [ProtoMember(3)]
 public string Message;
}

using System;
using ProtoBuf;
 
//添加特性,表示可以被ProtoBuf工具序列化
[ProtoContract]
public class NetModel {
 //添加特性,表示該字段可以被序列化,1可以理解為下標(biāo)
 [ProtoMember(1)] 
 public int ID;
 [ProtoMember(2)]
 public string Commit;
 [ProtoMember(3)]
 public string Message;
}

在Unity中添加測(cè)試腳本,介紹ProtoBuf工具的使用。

using System;
using System.IO;

public class Test : MonoBehaviour {

 void Start () {
  //創(chuàng)建對(duì)象
  NetModel item = new NetModel(){ID = 1, Commit = "LanOu", Message = "Unity"};
  //序列化對(duì)象
  byte[] temp = Serialize(item);
  //ProtoBuf的優(yōu)勢(shì)一:小
  Debug.Log(temp.Length);
  //反序列化為對(duì)象
  NetModel result = DeSerialize(temp);
  Debug.Log(result.Message);

 }

 // 將消息序列化為二進(jìn)制的方法
 // < param name="model">要序列化的對(duì)象< /param>
 private byte[] Serialize(NetModel model)
 {
  try {
   //涉及格式轉(zhuǎn)換,需要用到流,將二進(jìn)制序列化到流中
   using (MemoryStream ms = new MemoryStream()) {
    //使用ProtoBuf工具的序列化方法
    ProtoBuf.Serializer.Serialize<NetModel> (ms, model);
    //定義二級(jí)制數(shù)組,保存序列化后的結(jié)果
    byte[] result = new byte[ms.Length];
    //將流的位置設(shè)為0,起始點(diǎn)
    ms.Position = 0;
    //將流中的內(nèi)容讀取到二進(jìn)制數(shù)組中
    ms.Read (result, 0, result.Length);
    return result;
   }
  } catch (Exception ex) {
   Debug.Log ("序列化失敗: " + ex.ToString());
   return null;
  }
 }

 // 將收到的消息反序列化成對(duì)象
 // < returns>The serialize.< /returns>
 // < param name="msg">收到的消息.</param>
 private NetModel DeSerialize(byte[] msg)
 {
  try {
   using (MemoryStream ms = new MemoryStream()) {
    //將消息寫入流中
    ms.Write (msg, 0, msg.Length);
    //將流的位置歸0
    ms.Position = 0;
    //使用工具反序列化對(duì)象
    NetModel result = ProtoBuf.Serializer.Deserialize<NetModel> (ms);
    return result;
   }
  } catch (Exception ex) {  
    Debug.Log("反序列化失敗: " + ex.ToString());
    return null;
  }
 }
}

using System;
using System.IO;
 
public class Test : MonoBehaviour {
 
 void Start () {
  //創(chuàng)建對(duì)象
  NetModel item = new NetModel(){ID = 1, Commit = "LanOu", Message = "Unity"};
  //序列化對(duì)象
  byte[] temp = Serialize(item);
  //ProtoBuf的優(yōu)勢(shì)一:小
  Debug.Log(temp.Length);
  //反序列化為對(duì)象
  NetModel result = DeSerialize(temp);
  Debug.Log(result.Message);
 
 }
 
 // 將消息序列化為二進(jìn)制的方法
 // < param name="model">要序列化的對(duì)象< /param>
 private byte[] Serialize(NetModel model)
 {
  try {
   //涉及格式轉(zhuǎn)換,需要用到流,將二進(jìn)制序列化到流中
   using (MemoryStream ms = new MemoryStream()) {
    //使用ProtoBuf工具的序列化方法
    ProtoBuf.Serializer.Serialize<NetModel> (ms, model);
    //定義二級(jí)制數(shù)組,保存序列化后的結(jié)果
    byte[] result = new byte[ms.Length];
    //將流的位置設(shè)為0,起始點(diǎn)
    ms.Position = 0;
    //將流中的內(nèi)容讀取到二進(jìn)制數(shù)組中
    ms.Read (result, 0, result.Length);
    return result;
   }
  } catch (Exception ex) {
   Debug.Log ("序列化失敗: " + ex.ToString());
   return null;
  }
 }
 
 // 將收到的消息反序列化成對(duì)象
 // < returns>The serialize.< /returns>
 // < param name="msg">收到的消息.</param>
 private NetModel DeSerialize(byte[] msg)
 {
  try {
   using (MemoryStream ms = new MemoryStream()) {
    //將消息寫入流中
    ms.Write (msg, 0, msg.Length);
    //將流的位置歸0
    ms.Position = 0;
    //使用工具反序列化對(duì)象
    NetModel result = ProtoBuf.Serializer.Deserialize<NetModel> (ms);
    return result;
   }
  } catch (Exception ex) {  
    Debug.Log("反序列化失敗: " + ex.ToString());
    return null;
  }
 }
}

二、Unity中使用Socket實(shí)現(xiàn)時(shí)時(shí)通信

通信應(yīng)該實(shí)現(xiàn)的功能:

  • 服務(wù)器可以時(shí)時(shí)監(jiān)聽多個(gè)客戶端
  • 服務(wù)器可以時(shí)時(shí)監(jiān)聽某一個(gè)客戶端消息
  • 服務(wù)器可以時(shí)時(shí)給某一個(gè)客戶端發(fā)消息
  • 首先我們需要定義一個(gè)客戶端對(duì)象
using System;
using System.Net.Sockets;

// 表示一個(gè)客戶端
public class NetUserToken {
 //連接客戶端的Socket
 public Socket socket;
 //用于存放接收數(shù)據(jù)
 public byte[] buffer;

 public NetUserToken()
 {
  buffer = new byte[1024];
 }

 // 接受消息
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("接收到消息!");
 }

 // 發(fā)送消息
 //< param name="data">Data.< /param>
 public void Send(byte[] data)
 {  

 }
}

using System;
using System.Net.Sockets;
 
// 表示一個(gè)客戶端
public class NetUserToken {
 //連接客戶端的Socket
 public Socket socket;
 //用于存放接收數(shù)據(jù)
 public byte[] buffer;
 
 public NetUserToken()
 {
  buffer = new byte[1024];
 }
 
 // 接受消息
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("接收到消息!");
 }
 
 // 發(fā)送消息
 //< param name="data">Data.< /param>
 public void Send(byte[] data)
 {  
 
 }
}


然后實(shí)現(xiàn)我們的服務(wù)器代碼

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System;
using System.Net.Sockets;

public class NetServer{
 //單例腳本
 public static readonly NetServer Instance = new NetServer();
 //定義tcp服務(wù)器
 private Socket server;
 private int maxClient = 10;
 //定義端口
 private int port = 35353;
 //用戶池
 private Stack<NetUserToken> pools;
 private NetServer()
 {
  //初始化socket
  server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  server.Bind(new IPEndPoint(IPAddress.Any, port));

 }

 //開啟服務(wù)器
 public void Start()
 {
  server.Listen(maxClient);
  UnityEngine.Debug.Log("Server OK!");
  //實(shí)例化客戶端的用戶池
  pools = new Stack<NetUserToken>(maxClient);
  for(int i = 0; i < maxClient; i++)
  {
   NetUserToken usertoken = new NetUserToken();
   pools.Push(usertoken);
  }
  //可以異步接受客戶端, BeginAccept函數(shù)的第一個(gè)參數(shù)是回調(diào)函數(shù),當(dāng)有客戶端連接的時(shí)候自動(dòng)調(diào)用
  server.BeginAccept (AsyncAccept, null);
 }

 //回調(diào)函數(shù), 有客戶端連接的時(shí)候會(huì)自動(dòng)調(diào)用此方法
 private void AsyncAccept(IAsyncResult result)
 {
  try {
   //結(jié)束監(jiān)聽,同時(shí)獲取到客戶端
   Socket client = server.EndAccept(result);
   UnityEngine.Debug.Log("有客戶端連接");
   //來了一個(gè)客戶端
   NetUserToken userToken = pools.Pop();
   userToken.socket = client;
   //客戶端連接之后,可以接受客戶端消息
   BeginReceive(userToken);

   //尾遞歸,再次監(jiān)聽是否還有其他客戶端連入
   server.BeginAccept(AsyncAccept, null);
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }

 //異步監(jiān)聽消息
 private void BeginReceive(NetUserToken userToken)
 {
  try {
   //異步方法
   userToken.socket.BeginReceive(userToken.buffer, 0, userToken.buffer.Length, SocketFlags.None,
           EndReceive, userToken);
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }

 //監(jiān)聽到消息之后調(diào)用的函數(shù)
 private void EndReceive(IAsyncResult result)
 {
  try {
   //取出客戶端
   NetUserToken userToken = result.AsyncState as NetUserToken;
   //獲取消息的長(zhǎng)度
   int len = userToken.socket.EndReceive(result);
   if(len > 0)
   { 
    byte[] data = new byte[len];
    Buffer.BlockCopy(userToken.buffer, 0, data, 0, len);
    //用戶接受消息
    userToken.Receive(data);
    //尾遞歸,再次監(jiān)聽客戶端消息
    BeginReceive(userToken);
   }

  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
}

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System;
using System.Net.Sockets;
 
public class NetServer{
 //單例腳本
 public static readonly NetServer Instance = new NetServer();
 //定義tcp服務(wù)器
 private Socket server;
 private int maxClient = 10;
 //定義端口
 private int port = 35353;
 //用戶池
 private Stack<NetUserToken> pools;
 private NetServer()
 {
  //初始化socket
  server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  server.Bind(new IPEndPoint(IPAddress.Any, port));
 
 }
 
 //開啟服務(wù)器
 public void Start()
 {
  server.Listen(maxClient);
  UnityEngine.Debug.Log("Server OK!");
  //實(shí)例化客戶端的用戶池
  pools = new Stack<NetUserToken>(maxClient);
  for(int i = 0; i < maxClient; i++)
  {
   NetUserToken usertoken = new NetUserToken();
   pools.Push(usertoken);
  }
  //可以異步接受客戶端, BeginAccept函數(shù)的第一個(gè)參數(shù)是回調(diào)函數(shù),當(dāng)有客戶端連接的時(shí)候自動(dòng)調(diào)用
  server.BeginAccept (AsyncAccept, null);
 }
 
 //回調(diào)函數(shù), 有客戶端連接的時(shí)候會(huì)自動(dòng)調(diào)用此方法
 private void AsyncAccept(IAsyncResult result)
 {
  try {
   //結(jié)束監(jiān)聽,同時(shí)獲取到客戶端
   Socket client = server.EndAccept(result);
   UnityEngine.Debug.Log("有客戶端連接");
   //來了一個(gè)客戶端
   NetUserToken userToken = pools.Pop();
   userToken.socket = client;
   //客戶端連接之后,可以接受客戶端消息
   BeginReceive(userToken);
 
   //尾遞歸,再次監(jiān)聽是否還有其他客戶端連入
   server.BeginAccept(AsyncAccept, null);
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
 
 //異步監(jiān)聽消息
 private void BeginReceive(NetUserToken userToken)
 {
  try {
   //異步方法
   userToken.socket.BeginReceive(userToken.buffer, 0, userToken.buffer.Length, SocketFlags.None,
           EndReceive, userToken);
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
 
 //監(jiān)聽到消息之后調(diào)用的函數(shù)
 private void EndReceive(IAsyncResult result)
 {
  try {
   //取出客戶端
   NetUserToken userToken = result.AsyncState as NetUserToken;
   //獲取消息的長(zhǎng)度
   int len = userToken.socket.EndReceive(result);
   if(len > 0)
   { 
    byte[] data = new byte[len];
    Buffer.BlockCopy(userToken.buffer, 0, data, 0, len);
    //用戶接受消息
    userToken.Receive(data);
    //尾遞歸,再次監(jiān)聽客戶端消息
    BeginReceive(userToken);
   }
 
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
}


在Unity中開啟服務(wù)器,并使用C#控制臺(tái)模擬客戶端連接、發(fā)送消息操作。測(cè)試OK了,Unity中可以時(shí)時(shí)監(jiān)聽到消息。

using UnityEngine;
using System.Collections;

public class CreateServer : MonoBehaviour {

 void StartServer () {
  NetServer.Instance.Start();
 }

}

//C#控制臺(tái)工程

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace Temp
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   TcpClient tc = new TcpClient();
   IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35353);
   tc.Connect(ip);

   if(tc.Connected)
   {
    while(true)
    {

     string msg = Console.ReadLine();
     byte[] result = Encoding.UTF8.GetBytes(msg);
     tc.GetStream().Write(result, 0, result.Length);
    }
   }
   Console.ReadLine();
  }
 }
}

using UnityEngine;
using System.Collections;
 
public class CreateServer : MonoBehaviour {
 
 void StartServer () {
  NetServer.Instance.Start();
 }
 
}
 
//C#控制臺(tái)工程
 
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
 
namespace Temp
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   TcpClient tc = new TcpClient();
   IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35353);
   tc.Connect(ip);
 
   if(tc.Connected)
   {
    while(true)
    {
 
     string msg = Console.ReadLine();
     byte[] result = Encoding.UTF8.GetBytes(msg);
     tc.GetStream().Write(result, 0, result.Length);
    }
   }
   Console.ReadLine();
  }
 }
}

三、數(shù)據(jù)包的編碼和解碼

首先,舉個(gè)例子,這個(gè)月信用卡被媳婦刷爆了,面對(duì)房貸車貸的壓力,我只能選擇分期付款。。。

那么OK了,現(xiàn)在我想問一下,當(dāng)服務(wù)器向客戶端發(fā)送的數(shù)據(jù)過大時(shí)怎么辦呢?

當(dāng)服務(wù)器需要向客戶端發(fā)送一條很長(zhǎng)的數(shù)據(jù),也會(huì)“分期付款!”,服務(wù)器會(huì)把一條很長(zhǎng)的數(shù)據(jù)分成若干條小數(shù)據(jù),多次發(fā)送給客戶端。

可是,這樣就又有另外一個(gè)問題,客戶端接受到多條數(shù)據(jù)之后如何解析?

這里其實(shí)就是客戶端的解碼。server發(fā)數(shù)據(jù)一般采用“長(zhǎng)度+內(nèi)容”的格式,Client接收到數(shù)據(jù)之后,先提取出長(zhǎng)度來,然后根據(jù)長(zhǎng)度判斷內(nèi)容是否發(fā)送完畢。

再次重申,用戶在發(fā)送序列化好的消息的前,需要先編碼后再發(fā)送消息;用戶在接受消息后,需要解碼之后再解析數(shù)據(jù)(反序列化)。

using UnityEngine;
using System.Collections.Generic;
using System.IO;

// 編碼和解碼
public class NetEncode {

 // 將數(shù)據(jù)編碼 長(zhǎng)度+內(nèi)容
 /// < param name="data">內(nèi)容< /param>
 public static byte[] Encode(byte[] data)
 {
  //整形占四個(gè)字節(jié),所以聲明一個(gè)+4的數(shù)組
  byte[] result = new byte[data.Length + 4];
  //使用流將編碼寫二進(jìn)制
  MemoryStream ms = new MemoryStream();
  BinaryWriter br = new BinaryWriter(ms);
  br.Write(data.Length);
  br.Write(data);
  //將流中的內(nèi)容復(fù)制到數(shù)組中
  System.Buffer.BlockCopy(ms.ToArray(), 0, result, 0, (int)ms.Length);
  br.Close();
  ms.Close();
  return result;
 }

 // 將數(shù)據(jù)解碼
 // < param name="cache">消息隊(duì)列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //首先要獲取長(zhǎng)度,整形4個(gè)字節(jié),如果字節(jié)數(shù)不足4個(gè)字節(jié)
  if(cache.Count < 4)
  {
   return null;
  }
  //讀取數(shù)據(jù)
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //根據(jù)長(zhǎng)度,判斷內(nèi)容是否傳遞完畢
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //獲取數(shù)據(jù)
  byte[] result = br.ReadBytes(len);
  //清空消息池
  cache.Clear();
  //講剩余沒處理的消息存入消息池
  cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));

  return result;
 }
}

using UnityEngine;
using System.Collections.Generic;
using System.IO;
 
// 編碼和解碼
public class NetEncode {
 
 // 將數(shù)據(jù)編碼 長(zhǎng)度+內(nèi)容
 /// < param name="data">內(nèi)容< /param>
 public static byte[] Encode(byte[] data)
 {
  //整形占四個(gè)字節(jié),所以聲明一個(gè)+4的數(shù)組
  byte[] result = new byte[data.Length + 4];
  //使用流將編碼寫二進(jìn)制
  MemoryStream ms = new MemoryStream();
  BinaryWriter br = new BinaryWriter(ms);
  br.Write(data.Length);
  br.Write(data);
  //將流中的內(nèi)容復(fù)制到數(shù)組中
  System.Buffer.BlockCopy(ms.ToArray(), 0, result, 0, (int)ms.Length);
  br.Close();
  ms.Close();
  return result;
 }
 
 // 將數(shù)據(jù)解碼
 // < param name="cache">消息隊(duì)列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //首先要獲取長(zhǎng)度,整形4個(gè)字節(jié),如果字節(jié)數(shù)不足4個(gè)字節(jié)
  if(cache.Count < 4)
  {
   return null;
  }
  //讀取數(shù)據(jù)
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //根據(jù)長(zhǎng)度,判斷內(nèi)容是否傳遞完畢
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //獲取數(shù)據(jù)
  byte[] result = br.ReadBytes(len);
  //清空消息池
  cache.Clear();
  //講剩余沒處理的消息存入消息池
  cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));
 
  return result;
 }
}

用戶接受數(shù)據(jù)代碼如下:

using System;
using System.Collections.Generic;
using System.Net.Sockets;

// 表示一個(gè)客戶端
public class NetUserToken {
 //連接客戶端的Socket
 public Socket socket;
 //用于存放接收數(shù)據(jù)
 public byte[] buffer;
 //每次接受和發(fā)送數(shù)據(jù)的大小
 private const int size = 1024;

 //接收數(shù)據(jù)池
 private List<byte> receiveCache;
 private bool isReceiving;
 //發(fā)送數(shù)據(jù)池
 private Queue<byte[]> sendCache;
 private bool isSending;

 //接收到消息之后的回調(diào)
 public Action<NetModel> receiveCallBack;


 public NetUserToken()
 {
  buffer = new byte[size];
  receiveCache = new List<byte>();
  sendCache = new Queue<byte[]>();
 }

 // 服務(wù)器接受客戶端發(fā)送的消息
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("接收到數(shù)據(jù)");
  //將接收到的數(shù)據(jù)放入數(shù)據(jù)池中
  receiveCache.AddRange(data);
  //如果沒在讀數(shù)據(jù)
  if(!isReceiving)
  {
   isReceiving = true;
   ReadData();
  }
 }

 // 讀取數(shù)據(jù)
 private void ReadData()
 {
  byte[] data = NetEncode.Decode(ref receiveCache);
  //說明數(shù)據(jù)保存成功
  if(data != null)
  {
   NetModel item = NetSerilizer.DeSerialize(data);
   UnityEngine.Debug.Log(item.Message);
   if(receiveCallBack != null)
   {
    receiveCallBack(item);
   }
   //尾遞歸,繼續(xù)讀取數(shù)據(jù)
   ReadData();
  }
  else
  {
   isReceiving = false;
  }
 }

 // 服務(wù)器發(fā)送消息給客戶端
 public void Send()
 {
  try {
   if (sendCache.Count == 0) {
    isSending = false;
    return; 
   }
   byte[] data = sendCache.Dequeue ();
   int count = data.Length / size;
   int len = size;
   for (int i = 0; i < count + 1; i++) {
    if (i == count) {
     len = data.Length - i * size;
    }
    socket.Send (data, i * size, len, SocketFlags.None);
   }
   UnityEngine.Debug.Log("發(fā)送成功!");
   Send ();
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }

 public void WriteSendDate(byte[] data){
  sendCache.Enqueue(data);
  if(!isSending)
  {
   isSending = true;
   Send();
  }
 }
}

using System;
using System.Collections.Generic;
using System.Net.Sockets;
 
// 表示一個(gè)客戶端
public class NetUserToken {
 //連接客戶端的Socket
 public Socket socket;
 //用于存放接收數(shù)據(jù)
 public byte[] buffer;
 //每次接受和發(fā)送數(shù)據(jù)的大小
 private const int size = 1024;
 
 //接收數(shù)據(jù)池
 private List<byte> receiveCache;
 private bool isReceiving;
 //發(fā)送數(shù)據(jù)池
 private Queue<byte[]> sendCache;
 private bool isSending;
 
 //接收到消息之后的回調(diào)
 public Action<NetModel> receiveCallBack;
 
 
 public NetUserToken()
 {
  buffer = new byte[size];
  receiveCache = new List<byte>();
  sendCache = new Queue<byte[]>();
 }
 
 // 服務(wù)器接受客戶端發(fā)送的消息
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("接收到數(shù)據(jù)");
  //將接收到的數(shù)據(jù)放入數(shù)據(jù)池中
  receiveCache.AddRange(data);
  //如果沒在讀數(shù)據(jù)
  if(!isReceiving)
  {
   isReceiving = true;
   ReadData();
  }
 }
 
 // 讀取數(shù)據(jù)
 private void ReadData()
 {
  byte[] data = NetEncode.Decode(ref receiveCache);
  //說明數(shù)據(jù)保存成功
  if(data != null)
  {
   NetModel item = NetSerilizer.DeSerialize(data);
   UnityEngine.Debug.Log(item.Message);
   if(receiveCallBack != null)
   {
    receiveCallBack(item);
   }
   //尾遞歸,繼續(xù)讀取數(shù)據(jù)
   ReadData();
  }
  else
  {
   isReceiving = false;
  }
 }
 
 // 服務(wù)器發(fā)送消息給客戶端
 public void Send()
 {
  try {
   if (sendCache.Count == 0) {
    isSending = false;
    return; 
   }
   byte[] data = sendCache.Dequeue ();
   int count = data.Length / size;
   int len = size;
   for (int i = 0; i < count + 1; i++) {
    if (i == count) {
     len = data.Length - i * size;
    }
    socket.Send (data, i * size, len, SocketFlags.None);
   }
   UnityEngine.Debug.Log("發(fā)送成功!");
   Send ();
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
 
 public void WriteSendDate(byte[] data){
  sendCache.Enqueue(data);
  if(!isSending)
  {
   isSending = true;
   Send();
  }
 }
}

ProtoBuf網(wǎng)絡(luò)傳輸?shù)竭@里就全部完成了。

相關(guān)文章

  • C#實(shí)現(xiàn)在前端網(wǎng)頁(yè)彈出警告對(duì)話框(alert)的方法

    C#實(shí)現(xiàn)在前端網(wǎng)頁(yè)彈出警告對(duì)話框(alert)的方法

    這篇文章主要介紹了C#實(shí)現(xiàn)在前端網(wǎng)頁(yè)彈出警告對(duì)話框(alert)的方法,涉及C#通過自定義函數(shù)調(diào)用window.alert方法彈出對(duì)話框的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-04-04
  • C#多線程同步lock、Mutex的實(shí)現(xiàn)

    C#多線程同步lock、Mutex的實(shí)現(xiàn)

    本文主要介紹了C#多線程同步lock、Mutex的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • C#非矩形窗體實(shí)現(xiàn)方法

    C#非矩形窗體實(shí)現(xiàn)方法

    這篇文章主要介紹了C#非矩形窗體實(shí)現(xiàn)方法,涉及C#窗體操作的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • C#實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出任一Word圖表的通用呈現(xiàn)方法

    C#實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出任一Word圖表的通用呈現(xiàn)方法

    應(yīng)人才測(cè)評(píng)產(chǎn)品的需求,導(dǎo)出測(cè)評(píng)報(bào)告是其中一個(gè)重要的環(huán)節(jié),報(bào)告的文件類型也多種多樣,其中WORD輸出也扮演了一個(gè)重要的角色,本文給大家介紹了C#實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出任一Word圖表的通用呈現(xiàn)方法及一些體會(huì),需要的朋友可以參考下
    2023-10-10
  • C# wx獲取token的基本方法

    C# wx獲取token的基本方法

    這篇文章主要為大家詳細(xì)介紹了C# wx獲取token的基本方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • C#自定義事件及用法實(shí)例

    C#自定義事件及用法實(shí)例

    這篇文章主要介紹了C#自定義事件及用法,實(shí)例分析了C#中自定義事件的定義與使用技巧,需要的朋友可以參考下
    2015-05-05
  • C#實(shí)現(xiàn)簡(jiǎn)單過濾非法字符實(shí)例

    C#實(shí)現(xiàn)簡(jiǎn)單過濾非法字符實(shí)例

    這篇文章主要介紹了C#實(shí)現(xiàn)簡(jiǎn)單過濾非法字符的方法,涉及C#針對(duì)字符串遍歷與判斷的相關(guān)技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下
    2015-11-11
  • C#將PDF轉(zhuǎn)為多種圖像文件格式的方法(Png/Bmp/Emf/Tiff)

    C#將PDF轉(zhuǎn)為多種圖像文件格式的方法(Png/Bmp/Emf/Tiff)

    這里介紹將PDF轉(zhuǎn)換多種不同格式的圖像文件格式,如PNG,BMP,EMF,TIFF等,同時(shí),轉(zhuǎn)換文檔也分為轉(zhuǎn)換全部文檔和轉(zhuǎn)換部分文檔為圖片兩種情況,本文也將作進(jìn)一步介紹
    2018-02-02
  • C#中的高階函數(shù)介紹

    C#中的高階函數(shù)介紹

    這篇文章主要介紹了C#中的高階函數(shù)介紹,本文講解了接受函數(shù)、輸出函數(shù)、Currying(科里化)等內(nèi)容,需要的朋友可以參考下
    2015-04-04
  • C#獲取全部目錄和文件的簡(jiǎn)單實(shí)例

    C#獲取全部目錄和文件的簡(jiǎn)單實(shí)例

    這篇文章介紹了C#獲取全部目錄和文件的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下
    2013-10-10

最新評(píng)論

教育| 高州市| 鄯善县| 禄劝| 沙田区| 盐津县| 乐业县| 信丰县| 泽州县| 寿阳县| 柞水县| 阳东县| 独山县| 东山县| 深州市| 锡林郭勒盟| 浦城县| 玛曲县| 老河口市| 麦盖提县| 霍山县| 集贤县| 晴隆县| 洪江市| 略阳县| 舟山市| 南和县| 资阳市| 安新县| 巩留县| 海伦市| 德州市| 青川县| 华宁县| 旬阳县| 理塘县| 汾阳市| 延安市| 手机| 宿州市| 平和县|