Unity3D之C#用Socket傳數據包

JFPackage.cs

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
 
public class JFPackage
{
    //結構體序列化
    [System.Serializable]
    //4字節對齊 iphone 和 android上可以1字節對齊
    [StructLayout(LayoutKind.Sequential, Pack = 8)]
    public struct WorldPackage
    {
 
         public short   header;
         public short   total;
         public uint    no;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
         public byte[]  content;
          
         public WorldPackage(short _h , short _t, uint _n ,byte[] _c)
        {
            header = _h;
            total = _t;
            no = _n;
            content = _c;
        }
         
    };  

}
<h3 style="padding: 0px; margin: 0px 0px 2px; font-size: 10pt; color: rgb(0, 102, 0); font-family: "Microsoft YaHei", Verdana, sans-serif, SimSun;">JFSocket.cs</h3><pre name="code" class="java">using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
public class JFSocket
{
 
    //Socket客戶端對象
    private Socket clientSocket;
    //JFPackage.WorldPackage是我封裝的結構體,
    //在與服務器交互的時候會傳遞這個結構體
    //當客戶端接到到服務器返回的數據包時,我把結構體add存在鏈表中。
    public List<JFPackage.WorldPackage> worldpackage;
    //單例模式
    private static JFSocket instance;
    public static JFSocket GetInstance()
    {
        if (instance == null)
        {
            instance = new JFSocket();
        }
        return instance;
    }
 
    //單例的構造函數
    JFSocket()
    {
        //創建Socket對象, 這裏我的連接類型是TCP
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //服務器IP地址
        IPAddress ipAddress = IPAddress.Parse("192.168.1.106");
        //服務器端口
        IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 8800);
        //這是一個異步的建立連接,當連接建立成功時調用connectCallback方法
        IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
        //這裏做一個超時的監測,當連接超過5秒還沒成功表示超時
        bool success = result.AsyncWaitHandle.WaitOne(5000, true);
        if (!success)
        {
            //超時
            Closed();
            Debug.Log("connect Time Out");
        }
        else
        {
            //與socket建立連接成功,開啓線程接受服務端數據。
            worldpackage = new List<JFPackage.WorldPackage>();
            Thread thread = new Thread(new ThreadStart(ReceiveSorket));
            thread.IsBackground = true;
            thread.Start();
        }
    }
 
    private void connectCallback(IAsyncResult asyncConnect)
    {
        Debug.Log("connectSuccess");
    }
 
    private void ReceiveSorket()
    {
        //在這個線程中接受服務器返回的數據
        while (true)
        {
 
            if (!clientSocket.Connected)
            {
                //與服務器斷開連接跳出循環
                Debug.Log("Failed to clientSocket server.");
                clientSocket.Close();
                break;
            }
            try
            {
                //接受數據保存至bytes當中
                byte[] bytes = new byte[4096];
                //Receive方法中會一直等待服務端回發消息
                //如果沒有回發會一直在這裏等着。
                int i = clientSocket.Receive(bytes);
                if (i <= 0)
                {
                    clientSocket.Close();
                    break;
                }
 
                //這裏條件可根據你的情況來判斷。
                //因爲我目前的項目先要監測包頭長度,
                //我的包頭長度是2,所以我這裏有一個判斷
                if (bytes.Length > 8)
                {
                    SplitPackage(bytes, 0);
                }
                else
                {
                    Debug.Log("length is not  >  8");
                }
 
            }
            catch (Exception e)
            {
                Debug.Log("Failed to clientSocket error." + e);
                clientSocket.Close();
                break;
            }
        }
    }
 
    private void SplitPackage(byte[] bytes, int index)
    {
        //在這裏進行拆包,因爲一次返回的數據包的數量是不定的
        //所以需要給數據包進行查分。
        while (true)
        {
            //包頭是2個字節
            byte[] head = new byte[8];
            int headLengthIndex = index + 8;
            //把數據包的前兩個字節拷貝出來
            Array.Copy(bytes, index, head, 0, 8);
            //計算包頭的長度
            short length = BitConverter.ToInt16(head, 0);
            //當包頭的長度大於0 那麼需要依次把相同長度的byte數組拷貝出來
            if (length > 0)
            {
                byte[] data = new byte[length];
                //拷貝出這個包的全部字節數
                Array.Copy(bytes, headLengthIndex, data, 0, length);
                //把數據包中的字節數組強制轉換成數據包的結構體
                //BytesToStruct()方法就是用來轉換的
                //這裏需要和你們的服務端程序商量,
                JFPackage.WorldPackage wp = new JFPackage.WorldPackage();
                wp = (JFPackage.WorldPackage)BytesToStruct(data, wp.GetType());
                //把每個包的結構體對象添加至鏈表中。
                worldpackage.Add(wp);
                //將索引指向下一個包的包頭
                index = headLengthIndex + length;
 
            }
            else
            {
                //如果包頭爲0表示沒有包了,那麼跳出循環
                break;
            }
        }
    }
 
    //向服務端發送一條字符串
    //一般不會發送字符串 應該是發送數據包
    public void SendMessage(string str)
    {
        byte[] msg = Encoding.UTF8.GetBytes(str);
 
        if (!clientSocket.Connected)
        {
            clientSocket.Close();
            return;
        }
        try
        {
            //int i = clientSocket.Send(msg);
            IAsyncResult asyncSend = clientSocket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(sendCallback), clientSocket);
            bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);
            if (!success)
            {
                clientSocket.Close();
                Debug.Log("Failed to SendMessage server.");
            }
        }
        catch
        {
            Debug.Log("send message error");
        }
    }
 
    //向服務端發送數據包,也就是一個結構體對象
    public void SendMessage(object obj)
    {
 
        if (!clientSocket.Connected)
        {
            clientSocket.Close();
            return;
        }
        try
        {
            //先得到數據包的長度
            //short size = (short)Marshal.SizeOf(obj);
            //把數據包的長度寫入byte數組中
            //byte[] head = BitConverter.GetBytes(size);
            //把結構體對象轉換成數據包,也就是字節數組
            byte[] data = StructToBytes(obj);
 
            //此時就有了兩個字節數組,一個是標記數據包的長度字節數組, 一個是數據包字節數組,
            //同時把這兩個字節數組合併成一個字節數組
 
            //byte[] newByte = new byte[head.Length + data.Length];
            //Array.Copy(head, 0, newByte, 0, head.Length);
            //Array.Copy(data, 0, newByte, head.Length, data.Length);
 
            //計算出新的字節數組的長度
            //int length = Marshal.SizeOf(size) + Marshal.SizeOf(obj);
            Debug.Log("data len "+data.Length);
 
            //向服務端異步發送這個字節數組
            IAsyncResult asyncSend = clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallback), clientSocket);
            //監測超時
            bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);
            if (!success)
            {
                clientSocket.Close();
                Debug.Log("Time Out !");
            }
 
        }
        catch (Exception e)
        {
            Debug.Log("send message error: " + e);
        }
    }
 
    //結構體轉字節數組
    public byte[] StructToBytes(object structObj)
    {
 
        int size = Marshal.SizeOf(structObj);
        IntPtr buffer = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.StructureToPtr(structObj, buffer, false);
            byte[] bytes = new byte[size];
            Marshal.Copy(buffer, bytes, 0, size);
            return bytes;
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }
    }
    //字節數組轉結構體
    public object BytesToStruct(byte[] bytes, Type strcutType)
    {
        int size = Marshal.SizeOf(strcutType);
        IntPtr buffer = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.Copy(bytes, 0, buffer, size);
            return Marshal.PtrToStructure(buffer, strcutType);
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }
 
    }
 
    private void sendCallback(IAsyncResult asyncSend)
    {
 
    }
 
    //關閉Socket
    public void Closed()
    {
 
        if (clientSocket != null && clientSocket.Connected)
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
        clientSocket = null;
    }
 
}

test.cs


using UnityEngine;
using System.Collections;
 
public class test : MonoBehaviour {
    public JFSocket mJFsocket;
 
    // Use this for initialization
    void Start () {
        mJFsocket = JFSocket.GetInstance();
 
    }
     
    // Update is called once per frame
    void Update () {
     
    }
 
    void OnGUI()
    {
        if (GUI.Button(new Rect(100, 100, 200, 20), "click_"))
        {
            JFPackage.WorldPackage _p = new JFPackage.WorldPackage(127,12,10001,System.Text.Encoding.UTF8.GetBytes("walk"));
 
            mJFsocket.SendMessage(_p);
 
        }
         
    }
 
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章