In a TCP Socket server, if the server accepts a connection from a client then shuts down the socket associated with the client connection, the client can still send data to the server. No exception is raised by the client.
Why doesn't shutting down this socket cause an exception on the client-side?
I'd expect the client to attempt the send, realize it is no longer connected to a server socket then raise an exception. Obviously, this isn't happening which means either my assumption about how sockets should work here is incorrect (quite possible) or my code (below) is wrong. :-)
public async Task Demo()
{
var endPoint = new IPEndPoint(IPAddress.Loopback, 2100);
var serverTask = Task.Run(() =>
{
using (var listenSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
listenSocket.Bind(endPoint);
listenSocket.Listen(backlog: 1);
using (var connectionSocket = listenSocket.Accept())
{
connectionSocket.Shutdown(SocketShutdown.Both);
connectionSocket.Close();
}
}
});
using (var clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
clientSocket.Connect(endPoint);
await serverTask;
// Expect this to throw a SocketException--but it doesn't.
clientSocket.Send(new byte[] { 01 });
}
}