socket自动缓冲区大小

时间:2014-01-17 00:37:06

标签: c# .net sockets

我正在尝试创建一个C#套接字客户端,但是当我创建一个256

的缓冲区大小时
public class StateObject
{
    // Size of receive buffer.
    public const int BufferSize = 256; // the buffer size :/
    // Receive buffer.
    public byte[] Buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder Sb = new StringBuilder();
    public Socket WorkSocket = null;
}

我错过了一些收到的缓冲区并开始收到分离的缓冲区数组, 如果我创建它例如1000缓冲区大小我浪费太多内存如果我收到一个低大小的缓冲区是否有任何方法使缓冲区大小自动?

这是我用于连接回叫和接收回叫的代码

    private void OnConnectCallBack(IAsyncResult ar)
    {
        Socket.EndConnect(ar);
        Connection = Connection.Connected;
        if (OnConnect != null) OnConnect(this, CONNECTION_FROM.CLIENT);
        // Begin receiving the data from the remote device.
        Socket.BeginReceive(State.Buffer, 0, StateObject.BufferSize, 0, OnReceiveCallBack, State);
    }

    private void OnReceiveCallBack(IAsyncResult ar)
    {
        int bytesRead = Socket.EndReceive(ar);
        // There might be more data, so store the data received so far.
        if (OnReceive != null) OnReceive(this, State.Buffer, CONNECTION_FROM.CLIENT);
        // Get the rest of the data.
        Socket.BeginReceive(State.Buffer, 0, StateObject.BufferSize, 0,
            OnReceiveCallBack, State);
    }

0 个答案:

没有答案