异步客户端套接字,增加缓冲区大小

时间:2014-04-10 15:21:18

标签: c# .net sockets asynchronous

我实现了一个非常类似于this example的异步客户端套接字。我有什么理由不能大幅增加这个缓冲区大小吗?在此示例中,缓冲区大小为256字节。在许多情况下,我的应用程序最终会收到5,000 ++字节数据的数据。我应该增加缓冲区大小吗?我有什么理由不增加缓冲区大小吗?

每隔一段时间我就会遇到一些问题,即数据无序或者缺少一块(尚未确切地确认它是什么)。例如,有一次我收到了一些看起来像这样的损坏数据

Slice Id="0" layotartX='100'

我的数据中不存在名为layotartX的属性,它应该说layout = ...但是布局被切断了,后来又附加了其他数据。我计算了字节数,并注意到它被切断了恰好256个字节,恰好是我的缓冲区大小。增加我的缓冲区大小很可能会阻止这个问题的发生(数据无序)。无论如何,如第1段所述,我只是问是否有任何理由我不应该将缓冲区大小增加到5000字节甚至10,000字节。

添加一些代码。下面是我修改过的ReceiveCallback函数(参见上面链接的示例代码中的其余类。当ReceiveCallback接收数据时,它会调用“ReceiveSomeData”函数,我会'由于某种原因,每隔一段时间我就会出现乱序或丢失的数据。“ReceiveSomeData”函数位于名为“MyChitterChatter”的类中,“ReceiveCallback”函数位于名为“AsyncClient”的类中。所以当你看到ReceiveSomeData函数锁定“this”时,它会锁定MyChitterChatter类。是否可以通过说谎来解决我的问题?

    private static void ReceiveCallback( IAsyncResult ar )
    {
        AppDelegate appDel = (AppDelegate)UIApplication.SharedApplication.Delegate;

        try {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0) {
                // There might be more data, so store the data received so far.
                string stuffWeReceived = Encoding.ASCII.GetString(state.buffer,0,bytesRead);

                string debugString = "~~~~~ReceiveCallback~~~~~~ " + stuffWeReceived + " len = " + stuffWeReceived.Length + " bytesRead = " + bytesRead;

                Console.WriteLine(debugString);


                // Send this data to be received
                appDel.wallInteractionScreen.ChitterChatter.ReceiveSomeData(stuffWeReceived);

                // Get the rest of the data.
                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                    new AsyncCallback(ReceiveCallback), state);
            } else {
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        } 
        catch (Exception e) {
            Console.WriteLine("Error in AsyncClient ReceiveCallback: ");
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }


    public void ReceiveSomeData ( string data )
    {
        lock(this)
        {
            DataList_New.Add(data);

            // Update the keepalive when we receive ANY data at all
            IsConnected = true;
            LastDateTime_KeepAliveReceived = DateTime.Now;
        }
    }

1 个答案:

答案 0 :(得分:1)

是的,你绝对应该将缓冲区大小增加到更接近你期望在单次读取中获得的内容。对于大多数用途,32k或64k是不错的选择。

话虽如此,如果你使用TCP / IP套接字,数据永远不会出现“乱序”或“丢失一块”;如果你看到类似的东西,它就是代码中的错误,而不是套接字中的错误。如果您需要帮助,请分享您的代码。