Socket.Shutdown Method

Namespace: System.Net.Sockets

Assembly: System.Net.Sockets.dll

Shuts down both the send and receive capabilities of the Socket.

public void Shutdown(SocketShutdown how);

Parameters

Parameter Description
how A SocketShutdown enumeration value that specifies the portion of the connection to shut down.

Remarks

The Shutdown method gracefully closes the connection. You can specify whether to shut down the receive, send, or both parts of the connection.

After calling Shutdown, you should call Socket.Close to release all resources associated with the Socket.

Note: It is important to shut down the socket connection before closing it to ensure that all pending data is sent and received.

Exceptions

This method can throw the following exceptions:

Example

C# Example


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SocketShutdownExample
{
    public static void Main(string[] args)
    {
        // Example using TCP
        try
        {
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Loopback, 11000);
            listener.Bind(ipEndPoint);
            listener.Listen(100);

            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();
            Console.WriteLine("Connection accepted.");

            // ... perform send/receive operations ...

            // Shut down the connection for both sending and receiving
            Console.WriteLine("Shutting down socket.");
            handler.Shutdown(SocketShutdown.Both);

            // Close the socket
            handler.Close();
            Console.WriteLine("Socket closed.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}