程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#應用Protocol Buffer(ProtoBuf)停止Unity中的Socket通訊

C#應用Protocol Buffer(ProtoBuf)停止Unity中的Socket通訊

編輯:C#入門知識

C#應用Protocol Buffer(ProtoBuf)停止Unity中的Socket通訊。本站提示廣大學習愛好者:(C#應用Protocol Buffer(ProtoBuf)停止Unity中的Socket通訊)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用Protocol Buffer(ProtoBuf)停止Unity中的Socket通訊正文


起首來講一下本文中例子所要完成的功效:

  • 基於ProtoBuf序列化對象
  • 應用Socket完成不時通訊
  • 數據包的編碼息爭碼

上面來看詳細的步調:

1、Unity中應用ProtoBuf

導入DLL到Unity中,
創立收集傳輸的模子類:

using System;
using ProtoBuf;

//添加特征,表現可以被ProtoBuf對象序列化
[ProtoContract]
public class NetModel {
 //添加特征,表現該字段可以被序列化,1可以懂得為下標
 [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可以懂得為下標
 [ProtoMember(1)] 
 public int ID;
 [ProtoMember(2)]
 public string Commit;
 [ProtoMember(3)]
 public string Message;
}

在Unity中添加測試劇本,引見ProtoBuf對象的應用。

using System;
using System.IO;

public class Test : MonoBehaviour {

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

 }

 // 將新聞序列化為二進制的辦法
 // < param name="model">要序列化的對象< /param>
 private byte[] Serialize(NetModel model)
 {
  try {
   //觸及格局轉換,須要用到流,將二進制序列化到流中
   using (MemoryStream ms = new MemoryStream()) {
    //應用ProtoBuf對象的序列化辦法
    ProtoBuf.Serializer.Serialize<NetModel> (ms, model);
    //界說二級制數組,保留序列化後的成果
    byte[] result = new byte[ms.Length];
    //將流的地位設為0,肇端點
    ms.Position = 0;
    //將流中的內容讀取到二進制數組中
    ms.Read (result, 0, result.Length);
    return result;
   }
  } catch (Exception ex) {
   Debug.Log ("序列化掉敗: " + ex.ToString());
   return null;
  }
 }

 // 將收到的新聞反序列化成對象
 // < 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;
    //應用對象反序列化對象
    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 () {
  //創立對象
  NetModel item = new NetModel(){ID = 1, Commit = "LanOu", Message = "Unity"};
  //序列化對象
  byte[] temp = Serialize(item);
  //ProtoBuf的優勢一:小
  Debug.Log(temp.Length);
  //反序列化為對象
  NetModel result = DeSerialize(temp);
  Debug.Log(result.Message);
 
 }
 
 // 將新聞序列化為二進制的辦法
 // < param name="model">要序列化的對象< /param>
 private byte[] Serialize(NetModel model)
 {
  try {
   //觸及格局轉換,須要用到流,將二進制序列化到流中
   using (MemoryStream ms = new MemoryStream()) {
    //應用ProtoBuf對象的序列化辦法
    ProtoBuf.Serializer.Serialize<NetModel> (ms, model);
    //界說二級制數組,保留序列化後的成果
    byte[] result = new byte[ms.Length];
    //將流的地位設為0,肇端點
    ms.Position = 0;
    //將流中的內容讀取到二進制數組中
    ms.Read (result, 0, result.Length);
    return result;
   }
  } catch (Exception ex) {
   Debug.Log ("序列化掉敗: " + ex.ToString());
   return null;
  }
 }
 
 // 將收到的新聞反序列化成對象
 // < 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;
    //應用對象反序列化對象
    NetModel result = ProtoBuf.Serializer.Deserialize<NetModel> (ms);
    return result;
   }
  } catch (Exception ex) {  
    Debug.Log("反序列化掉敗: " + ex.ToString());
    return null;
  }
 }
}

2、Unity中應用Socket完成不時通訊

通訊應當完成的功效:

  • 辦事器可以不時監聽多個客戶端
  • 辦事器可以不時監聽某一個客戶端新聞
  • 辦事器可以不時給某一個客戶端發新聞
  • 起首我們須要界說一個客戶端對象
using System;
using System.Net.Sockets;

// 表現一個客戶端
public class NetUserToken {
 //銜接客戶真個Socket
 public Socket socket;
 //用於寄存吸收數據
 public byte[] buffer;

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

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

 // 發送新聞
 //< param name="data">Data.< /param>
 public void Send(byte[] data)
 {  

 }
}

using System;
using System.Net.Sockets;
 
// 表現一個客戶端
public class NetUserToken {
 //銜接客戶真個Socket
 public Socket socket;
 //用於寄存吸收數據
 public byte[] buffer;
 
 public NetUserToken()
 {
  buffer = new byte[1024];
 }
 
 // 接收新聞
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("吸收到新聞!");
 }
 
 // 發送新聞
 //< param name="data">Data.< /param>
 public void Send(byte[] data)
 {  
 
 }
}


然後完成我們的辦事器代碼

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辦事器
 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));

 }

 //開啟辦事器
 public void Start()
 {
  server.Listen(maxClient);
  UnityEngine.Debug.Log("Server OK!");
  //實例化客戶真個用戶池
  pools = new Stack<NetUserToken>(maxClient);
  for(int i = 0; i < maxClient; i++)
  {
   NetUserToken usertoken = new NetUserToken();
   pools.Push(usertoken);
  }
  //可以異步接收客戶端, BeginAccept函數的第一個參數是回調函數,當有客戶端銜接的時刻主動挪用
  server.BeginAccept (AsyncAccept, null);
 }

 //回調函數, 有客戶端銜接的時刻會主動挪用此辦法
 private void AsyncAccept(IAsyncResult result)
 {
  try {
   //停止監聽,同時獲得到客戶端
   Socket client = server.EndAccept(result);
   UnityEngine.Debug.Log("有客戶端銜接");
   //來了一個客戶端
   NetUserToken userToken = pools.Pop();
   userToken.socket = client;
   //客戶端銜接以後,可以接收客戶端新聞
   BeginReceive(userToken);

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

 //異步監聽新聞
 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());
  }
 }

 //監聽到新聞以後挪用的函數
 private void EndReceive(IAsyncResult result)
 {
  try {
   //掏出客戶端
   NetUserToken userToken = result.AsyncState as NetUserToken;
   //獲得新聞的長度
   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);
    //尾遞歸,再次監聽客戶端新聞
    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辦事器
 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));
 
 }
 
 //開啟辦事器
 public void Start()
 {
  server.Listen(maxClient);
  UnityEngine.Debug.Log("Server OK!");
  //實例化客戶真個用戶池
  pools = new Stack<NetUserToken>(maxClient);
  for(int i = 0; i < maxClient; i++)
  {
   NetUserToken usertoken = new NetUserToken();
   pools.Push(usertoken);
  }
  //可以異步接收客戶端, BeginAccept函數的第一個參數是回調函數,當有客戶端銜接的時刻主動挪用
  server.BeginAccept (AsyncAccept, null);
 }
 
 //回調函數, 有客戶端銜接的時刻會主動挪用此辦法
 private void AsyncAccept(IAsyncResult result)
 {
  try {
   //停止監聽,同時獲得到客戶端
   Socket client = server.EndAccept(result);
   UnityEngine.Debug.Log("有客戶端銜接");
   //來了一個客戶端
   NetUserToken userToken = pools.Pop();
   userToken.socket = client;
   //客戶端銜接以後,可以接收客戶端新聞
   BeginReceive(userToken);
 
   //尾遞歸,再次監聽能否還有其他客戶端連入
   server.BeginAccept(AsyncAccept, null);
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
 
 //異步監聽新聞
 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());
  }
 }
 
 //監聽到新聞以後挪用的函數
 private void EndReceive(IAsyncResult result)
 {
  try {
   //掏出客戶端
   NetUserToken userToken = result.AsyncState as NetUserToken;
   //獲得新聞的長度
   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);
    //尾遞歸,再次監聽客戶端新聞
    BeginReceive(userToken);
   }
 
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
}


在Unity中開啟辦事器,並應用C#掌握台模仿客戶端銜接、發送新聞操作。測試OK了,Unity中可以不時監聽到新聞。

using UnityEngine;
using System.Collections;

public class CreateServer : MonoBehaviour {

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

}

//C#掌握台工程

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#掌握台工程
 
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();
  }
 }
}

3、數據包的編碼息爭碼

起首,舉個例子,這個月信譽卡被媳婦刷爆了,面臨房貸車貸的壓力,我只能選擇分期付款。。。

那末OK了,如今我想問一下,當辦事器向客戶端發送的數據過年夜時怎樣辦呢?

當辦事器須要向客戶端發送一條很長的數據,也會“分期付款!”,辦事器會把一條很長的數據分紅若干條小數據,屢次發送給客戶端。

可是,如許就又有別的一個成績,客戶端接收到多條數據以後若何解析?

這裡其實就是客戶真個解碼。server發數據普通采取“長度+內容”的格局,Client吸收到數據以後,先提掏出長度來,然後依據長度斷定內容能否發送終了。

再次重申,用戶在發送序列化好的新聞的前,須要先編碼後再發送新聞;用戶在接收新聞後,須要解碼以後再解析數據(反序列化)。

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

// 編碼息爭碼
public class NetEncode {

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

 // 將數據解碼
 // < param name="cache">新聞隊列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //起首要獲得長度,整形4個字節,假如字節數缺乏4個字節
  if(cache.Count < 4)
  {
   return null;
  }
  //讀取數據
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //依據長度,斷定內容能否傳遞終了
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //獲得數據
  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 {
 
 // 將數據編碼 長度+內容
 /// < param name="data">內容< /param>
 public static byte[] Encode(byte[] data)
 {
  //整形占四個字節,所以聲明一個+4的數組
  byte[] result = new byte[data.Length + 4];
  //應用流將編碼寫二進制
  MemoryStream ms = new MemoryStream();
  BinaryWriter br = new BinaryWriter(ms);
  br.Write(data.Length);
  br.Write(data);
  //將流中的內容復制到數組中
  System.Buffer.BlockCopy(ms.ToArray(), 0, result, 0, (int)ms.Length);
  br.Close();
  ms.Close();
  return result;
 }
 
 // 將數據解碼
 // < param name="cache">新聞隊列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //起首要獲得長度,整形4個字節,假如字節數缺乏4個字節
  if(cache.Count < 4)
  {
   return null;
  }
  //讀取數據
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //依據長度,斷定內容能否傳遞終了
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //獲得數據
  byte[] result = br.ReadBytes(len);
  //清空新聞池
  cache.Clear();
  //講殘剩沒處置的新聞存入新聞池
  cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));
 
  return result;
 }
}

用戶接收數據代碼以下:

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

// 表現一個客戶端
public class NetUserToken {
 //銜接客戶真個Socket
 public Socket socket;
 //用於寄存吸收數據
 public byte[] buffer;
 //每次接收和發送數據的年夜小
 private const int size = 1024;

 //吸收數據池
 private List<byte> receiveCache;
 private bool isReceiving;
 //發送數據池
 private Queue<byte[]> sendCache;
 private bool isSending;

 //吸收到新聞以後的回調
 public Action<NetModel> receiveCallBack;


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

 // 辦事器接收客戶端發送的新聞
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("吸收到數據");
  //將吸收到的數據放入數據池中
  receiveCache.AddRange(data);
  //假如沒在讀數據
  if(!isReceiving)
  {
   isReceiving = true;
   ReadData();
  }
 }

 // 讀取數據
 private void ReadData()
 {
  byte[] data = NetEncode.Decode(ref receiveCache);
  //解釋數據保留勝利
  if(data != null)
  {
   NetModel item = NetSerilizer.DeSerialize(data);
   UnityEngine.Debug.Log(item.Message);
   if(receiveCallBack != null)
   {
    receiveCallBack(item);
   }
   //尾遞歸,持續讀取數據
   ReadData();
  }
  else
  {
   isReceiving = false;
  }
 }

 // 辦事器發送新聞給客戶端
 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("發送勝利!");
   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;
 
// 表現一個客戶端
public class NetUserToken {
 //銜接客戶真個Socket
 public Socket socket;
 //用於寄存吸收數據
 public byte[] buffer;
 //每次接收和發送數據的年夜小
 private const int size = 1024;
 
 //吸收數據池
 private List<byte> receiveCache;
 private bool isReceiving;
 //發送數據池
 private Queue<byte[]> sendCache;
 private bool isSending;
 
 //吸收到新聞以後的回調
 public Action<NetModel> receiveCallBack;
 
 
 public NetUserToken()
 {
  buffer = new byte[size];
  receiveCache = new List<byte>();
  sendCache = new Queue<byte[]>();
 }
 
 // 辦事器接收客戶端發送的新聞
 // < param name="data">Data.< /param>
 public void Receive(byte[] data)
 {
  UnityEngine.Debug.Log("吸收到數據");
  //將吸收到的數據放入數據池中
  receiveCache.AddRange(data);
  //假如沒在讀數據
  if(!isReceiving)
  {
   isReceiving = true;
   ReadData();
  }
 }
 
 // 讀取數據
 private void ReadData()
 {
  byte[] data = NetEncode.Decode(ref receiveCache);
  //解釋數據保留勝利
  if(data != null)
  {
   NetModel item = NetSerilizer.DeSerialize(data);
   UnityEngine.Debug.Log(item.Message);
   if(receiveCallBack != null)
   {
    receiveCallBack(item);
   }
   //尾遞歸,持續讀取數據
   ReadData();
  }
  else
  {
   isReceiving = false;
  }
 }
 
 // 辦事器發送新聞給客戶端
 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("發送勝利!");
   Send ();
  } catch (Exception ex) {
   UnityEngine.Debug.Log(ex.ToString());
  }
 }
 
 public void WriteSendDate(byte[] data){
  sendCache.Enqueue(data);
  if(!isSending)
  {
   isSending = true;
   Send();
  }
 }
}

ProtoBuf收集傳輸到這裡就全體完成了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved