TCP客户端有时会合并数据包

时间:2016-01-13 23:36:53

标签: c# .net tcp mono unity-container

在Unity应用程序中,我每秒通过TCP接收160个JSON对象。我的阅读代码似乎在这样的速度下挣扎,而且有几次没有processData它们作为单个消息。当我试图创建一个JSONObject`时,我会得到类似这样的东西

  

不正确的JSON   格式:右""数据" {"类型":"柔性""手势":"开&# 34;,"数据":[0.11425240454677936,0.11582253631723596,0.0947054436987323,0]}} {"类型":"右""数据" :{"类型":"传感器""数据":[0.98638916015625,-0.0802001953125,0.08880615234375,-0.11248779296875,空]}} {"类型& #34;:"右""数据" {"类型":"柔性""手势&#34 ;: "开""数据":[0.11192072282133489,0.11739301138594425,0.09271687795177729,0]}} {"类型":"右"&# 34;数据" {"类型":"传感器""数据":[0.98638916015625,-0.0802001953125,0.08880615234375,-0.11248779296875,空]}} {"类型":"右",

这是我的数据处理功能:

bool ProcessData()
{
    string temp = System.Text.Encoding.Default.GetString(readBuffer);
    //Debug.Log(string.Format("Client recv: '{0}'", temp));

    JSONObject obj = new JSONObject(temp);
}

这是我的TCP代码:

void connectToHub () {
    readBuffer = new byte[512];
    EndPoint endpoint;
    if (this.useUnixSocket == true) {
        endpoint = new UnixEndPoint(SOCKET_LOCATION);
    } else {
        endpoint = new IPEndPoint(this.ipAdress, this.port);
    }

    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    try {
        IAsyncResult result = client.BeginConnect(endpoint, 
                                    new AsyncCallback(this.EndConnect), 
                                    null);
        bool connectSuccess = result.AsyncWaitHandle.WaitOne(System.TimeSpan.FromSeconds(10));

        if (!connectSuccess){
            client.Close();
            Debug.LogError(string.Format("Client unable to connect. Failed"));
        }

    }
    catch(SystemException e) {
        Debug.LogError(string.Format("Client exception on beginconnect: {0}", e.Message));
    }

}

void EndConnect(IAsyncResult iar)
{
    client.EndConnect(iar);
    client.NoDelay = true;
    ReceiveData();
}


void ReceiveData()
{
    client.BeginReceive(readBuffer, 0, readBuffer.Length, SocketFlags.None, EndReceiveData, client);
}

void EndReceiveData(System.IAsyncResult iar)
{
    int numBytesReceived = client.EndReceive(iar);
    if (numBytesReceived > 0){
        this.ProcessData();

    }           
    // Continue receiving data
    ReceiveData();
}

1 个答案:

答案 0 :(得分:1)

在我看来,有时您会在数据全部到达之前开始处理数据。当您通过TCP接收一些数据时,您正在调用EndReceiveData。如果所有数据都适合刚刚到达的数据包,那么您没有问题。但是,如果数据大于数据包,那么在开始解析之前,你真的应该读取该json对象的所有数据包。