Socket.Close()

Method

public void Close()

Closes the Socket connection.

Remarks

The Close method releases all resources associated with the Socket. If the Socket is connected, it will attempt to send any buffered data before closing the connection. It is recommended to call Close when you are finished with the Socket object. Calling Close multiple times on the same Socket is a no-op after the first call.

You can also use the using statement to ensure that the Close method is called automatically when the scope of the Socket object is exited.

Example

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

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

            // Connect to a remote host by specifying IP address and port.
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
            socket.Connect(remoteEndPoint);

            Console.WriteLine("Socket connected to {0}", socket.RemoteEndPoint.ToString());

            // Some operations with the socket...
            byte[] msg = System.Text.Encoding.ASCII.GetBytes("Test message.");
            socket.Send(msg);

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

Exceptions

  • ObjectDisposedException: The Socket has been closed.
  • SocketException: An error occurred when trying to access the socket.

See Also