套接字没有丢弃"会阻塞" SocketException

时间:2016-03-23 17:56:56

标签: c# sockets socketexception

我试图强制套接字抛出SocketException错误代码"会阻塞"通过溢出可用缓冲区发送数据时,我无法实现它。这是一个我认为会表现出这种行为的小型控制台应用程序:

namespace BlockingSocketTest
{
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    internal class Program
    {
        const int Port = 65111;
        const int BufferSize = 4;

        static void Main(string[] args)
        {
            // Create the server
            Socket server = new Socket(SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Loopback, Port));
            server.Listen(1);
            server.BeginAccept(HandleAcceptConnection, server);

            // Create the client
            Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp);
            client.SendBufferSize = BufferSize;
            client.Blocking = false;
            client.Connect(new IPEndPoint(IPAddress.Loopback, Port));

            // Sleep to ensure HandleAcceptConnection completes
            Thread.Sleep(1000);

            // Send too much data
            Console.WriteLine("Sending data to the server");
            int bytesSent = client.Send(new byte[BufferSize * 3]);
            Console.WriteLine($"Sent {bytesSent} bytes");
        }

        static void HandleAcceptConnection(IAsyncResult asyncResult)
        {
            Socket server = (Socket)asyncResult.AsyncState;
            Socket clientConnection = server.EndAccept(asyncResult);
            Console.WriteLine("Got a connection from " + clientConnection.RemoteEndPoint);

            // Make the buffer small, and don't read any data
            clientConnection.ReceiveBufferSize = BufferSize;
        }
    }
}

我将发送和接收缓冲区大小设置为4,然后发送12个字节,从不读取接收方的任何数据。我的理解是:

  • 4个字节将被发送到侦听套接字并坐在那里直到我读它们
  • 4个字节将位于发送套接字中,直到接收方有空间
  • 剩余的4个字节将导致SocketException

然而,在运行时,它清楚地发送了所有12个字节:

Got a connection from [::ffff:127.0.0.1]:65009
Sending data to the server
Sent 12 bytes

我在这里误解了什么?什么是额外的4个字节?

0 个答案:

没有答案