c# - 如果缓冲区太小,是否可以防止异常?

标签 c# arrays sockets asynchronous udp

每当我的服务器应用程序收到一个对于缓冲区来说太大的数据包时,在调用Socket.EndReceiveFrom时它就会崩溃。这是我的代码如下所示:

static EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

static void Main(string[] args)
{
    socket.Bind(new IPEndPoint(IPAddress.Any, 1234));
    Receive();
    Console.WriteLine("Receiving ...");

    for (; ; ) ;
}

static void Receive()
{
    byte[] buffer = new byte[64];
    socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remote, ReceiveFromCallback, buffer);
}

static void ReceiveFromCallback(IAsyncResult result)
{
    EndPoint theRemote = new IPEndPoint(IPAddress.Any, 0);
    byte[] buffer = (byte[])result.AsyncState;

    // the following for loop is irrelevant for this question - it simply outputs the received data as hex numbers
    for (int x = 0; x < 8; x++)
    {
        Console.Write("  ");
        for (int y = 0; y < 8; y++)
        {
            string hex = Convert.ToString(buffer[(x * 8) + y], 16);
            Console.Write((hex.Length == 1 ? "0" : "") + hex + " ");
        }
        Console.WriteLine();
    }

    // the following line of code crashes the application if the received message is larger than 64 bytes
    socket.EndReceiveFrom(result, ref theRemote);
}

如果接收到的数据包大于64个字节,则我的应用程序将抛出SocketException,其内容如下:

A message which was sent over the datagram socket was too large for the internal data buffer or another network limit, or the buffer used for receiving the datagram was too small.



请注意,这不是原始消息文本。由于我正在使用德语版的Visual Studio,因此我不得不将其翻译回去。

ReceiveFromCallback的“buffer”变量仅包含消息的前64个字节(如果大于)。因此,检查“缓冲区”是否包含64个以上的字节不是一个选择。

所以我的问题是:

我需要调用EndReceiveFrom();吗?为什么要称呼它?如何检查收到的消息对于缓冲区而言是否太大?

最佳答案

From MSDN:

Within the callback method, call the AsyncState method of the IAsyncResult to obtain the state object passed to the BeginReceiveFrom method. Extract the receiving Socket from this state object. After obtaining the Socket, you can call the EndReceiveFrom method to successfully complete the read operation and return the number of bytes read.



因此,您应该在回调中调用EndReceiveFrom(就像您一样)。只需捕获异常,您的应用程序就不会“崩溃”。

关于c# - 如果缓冲区太小,是否可以防止异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245738/

相关文章:

python - TCP服务器无法在Python中正确接收数据

c# - 以编程方式确定代码是否在 IIS Express 下运行

c# - 更改容量时出现 StringBuilder 异常!

c# - 我们如何取消选中单选按钮

javascript - 如何在函数上创建数组显示?

python - Tkinter .after 方法卡住窗口?

c# - sqlite EF6代码首先不创建表

c++ - 声明 char[][512]?

java - 搜索字符串数组

c++ - 通过ip访问类