Namespace: System.Net.Sockets
Declaration: public enum SocketShutdown
Specifies the direction for shutting down a Socket connection. This enumeration is used by the Socket.Shutdown method.
When you call the Socket.Shutdown method, you specify how you want to close the connection. You can choose to stop receiving data, stop sending data, or stop both.
Receive, the socket will no longer accept incoming data.Send, the socket will no longer send outgoing data.Both, the socket will no longer send or receive data.This method is useful for gracefully closing a connection. For example, after sending all the data you need, you can call Socket.Shutdown with Send to signal the other end that you are done sending data. The other end can then acknowledge this and close the connection as well.
The following C# code demonstrates how to use the SocketShutdown enumeration to close a socket connection:
using System;
using System.Net;
using System.Net.Sockets;
public class Example
{
public static void Main()
{
// Assume 'clientSocket' is an already connected Socket object.
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// ... connection logic ...
try
{
// Send some data...
byte[] message = System.Text.Encoding.ASCII.GetBytes("Hello, server!");
clientSocket.Send(message);
// Gracefully shut down sending.
Console.WriteLine("Shutting down send stream.");
clientSocket.Shutdown(SocketShutdown.Send);
// Receive confirmation (optional, depends on protocol)
// ... receive logic ...
Console.WriteLine("Connection closed gracefully.");
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e.ToString());
}
finally
{
// Close the socket.
if (clientSocket.Connected)
{
clientSocket.Close();
}
}
}
}