C# “插座未被抛出”;将阻止;SocketException
我试图强制套接字抛出一个C# “插座未被抛出”;将阻止;SocketException,c#,sockets,socketexception,C#,Sockets,Socketexception,我试图强制套接字抛出一个SocketException,在发送数据时,通过过量填充可用缓冲区,错误代码为“will block”,但我无法让它发生。下面是一个小型控制台应用程序,我认为它会表现出以下行为: namespace BlockingSocketTest { using System; using System.Linq; using System.Net; using System.Net.Sockets; using System.Thread
SocketException
,在发送数据时,通过过量填充可用缓冲区,错误代码为“will block”,但我无法让它发生。下面是一个小型控制台应用程序,我认为它会表现出以下行为:
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个字节将存放在发送套接字中
- 剩余的4个字节将导致
SocketException
从[::ffff:127.0.0.1]:65009获得连接
正在向服务器发送数据
发送了12个字节
我在这里误解了什么?是什么保存了这些额外的4个字节?我可以问一下,如果您三次发送4个字节,而不是一次发送12个字节,会发生什么情况吗?类似的行为,所有4个字节都可以。