Unity客戶端長度信息法解決Socket粘包問題

客戶端源代碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using UnityEngine.UI;
using System;
using System.Linq;

public class Echo : MonoBehaviour
{
    //定義套接字
    Socket socket;
    //UGUI
    public InputField Input;
    public Text text;
    //緩衝區
    byte[] readbuff=new byte[1024];
    //緩衝區數據長度
    int buffCount=0;
    string recStr="";

    //異步連接
    public void Connection()
    {
        socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        socket.BeginConnect("127.0.0.1",8888,connectCallback,socket);
    }

    //連接回調
    public void connectCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket=(Socket) ar.AsyncState;
            socket.EndConnect(ar);
            Debug.Log("connect succed");
        }
        catch(SocketException e)
        {
            Debug.Log("socket fail"+e.ToString());
        }
        socket.BeginReceive(readbuff,buffCount,1024-buffCount,0,receivecallback,socket);
    }

    //接收回調
    public void receivecallback(IAsyncResult ar)
    {
        try
        {
             Socket socket=(Socket) ar.AsyncState;
             int count=socket.EndReceive(ar);
             buffCount+=count;
             //處理二進制消息
             OnReceiveData();
             string s=System.Text.Encoding.Default.GetString(readbuff,0,count);
             recStr=s+"\n"+recStr;
             socket.BeginReceive(readbuff,buffCount,1024-buffCount,0,receivecallback,socket);
        }
        catch(SocketException e)
        {
            Debug.Log("socket receive fail"+e.ToString());
        }
    }

    //異步發送
    public void Send()
    {
        string sendStr=Input.text;
        byte[] bodyBytes=System.Text.Encoding.Default.GetBytes(sendStr);
        Int16 len=(Int16)bodyBytes.Length;
        byte[] lenBytes=BitConverter.GetBytes(len);
        byte[] sendbytes=lenBytes.Concat(bodyBytes).ToArray();
        socket.BeginSend(sendbytes,0,sendbytes.Length,0,sendcallback,socket);
    }

    //發送回調
    private void sendcallback(IAsyncResult ar)
    {
        try
        {
            Socket socket=(Socket) ar.AsyncState;
            int count=socket.EndSend(ar);
            Debug.Log("Socket send succ ,number is:"+count);
        }
        catch(SocketException e)
        {
            Debug.Log("socket send erro:"+e.ToString());
        }
    }

    //更新UGUI界面的文本框
    public void Update() 
    {
        text.text=recStr;
    }

    //接收數據處理
    public void OnReceiveData()
    {
        Debug.Log("[Recv 1] buffercount="+buffCount);  //接收的總字節數(含長度)
        Debug.Log("[Recv 2] readbuffer="+BitConverter.ToString(readbuff));  //顯示接收的數據的內容
        //消息長度小於2,不做處理
        if(buffCount<=2)
        {
            return;
        }
        Int16 bodyLength=BitConverter.ToInt16(readbuff,0);  //消息體長度
        Debug.Log("[Recv 3] bodylength="+bodyLength);   //顯示消息體長度
        //消息長度大於2,但是不足長度,不做處理
        if(buffCount<2+bodyLength)
        {
            return;
        }
        string s=System.Text.Encoding.UTF8.GetString(readbuff,2,bodyLength);  //處理消息
        Debug.Log("[Recv 4] s="+s);   //顯示消息內容
        //更新緩衝區
        int start=2+bodyLength;    //更新起始位置
        int count=buffCount-start;     //更新計數
        Array.Copy(readbuff,start,readbuff,0,count);     //緩衝區移位
        buffCount-=start;
        Debug.Log("[Recv 5] buffCount="+buffCount);   //顯示計數
        recStr=s+"\n"+recStr;
        //繼續讀消息
        OnReceiveData();
    }
}

 

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