This documentation is archived and is not being maintained.

Socket.Close Method

Closes the Socket connection and releases all associated resources.

[Visual Basic]
Public Sub Close()
public void Close();
public: void Close();
public function Close();


The Close method closes the the remote host connection and releases all managed and unmanaged resources associated with the Socket. Upon closing, the Connected property is set to false.

For connection-oriented protocols, it is recommended that you call Shutdown before calling the Close method. This ensures that all data is sent and received on the connected socket before it is closed.

If you need to call Close without first calling Shutdown, you can ensure that data queued for outgoing transmission will be sent by setting the DontLinger Socket option to false and specifying a non-zero time-out interval. Close will then block until this data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.

Note   To set the DontLinger socket option to false, create a LingerOption, set the enabled property to false, and set the LingerTime property to the desired time out period. Use this LingerOption along with the DontLinger socket option to call the SetSocketOption method.


[Visual Basic, C#, C++] The following example closes a Socket.

[Visual Basic] 
If aSocket.Connected Then
    Console.WriteLine("Winsock error: " _
       + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()))
End If

if (aSocket.Connected) {
   Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );

if (aSocket->Connected) {
   Console::WriteLine(S"Winsock error: {0}", Convert::ToString(System::Runtime::InteropServices::Marshal::GetLastWin32Error()) );

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.


Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Socket Class | Socket Members | System.Net.Sockets Namespace | Shutdown | DontLinger