System.Net.Sockets Namespace
Provides classes that enable low-level network programming.
Class: Socket
Provides the Socket class, which supports unreliable datagram, and reliable sequenced, two-way connection-based byte streams as provided in the Winsock catalog of Windows Sockets applications.
Method: Close()
1 public void Close();
Remarks
The Close method releases all resources associated with the Socket object. If you are using a connection-oriented Socket, such as one that uses the TCP protocol, calling Close will also close the connection. After calling Close, you can no longer use the Socket object.
The Close method is equivalent to calling the Dispose() method.
Return Value
This method does not return a value.
Exceptions
This method does not typically throw exceptions.
Example
The following code example demonstrates how to create, connect, send data, receive data, and then close a TCP socket.
// Assume 'socket' is a connected Socket object
try
{
// Send some data...
byte[] sendBuffer = System.Text.Encoding.ASCII.GetBytes("Hello Server!");
socket.Send(sendBuffer);
// Receive some data...
byte[] receiveBuffer = new byte[1024];
int bytesReceived = socket.Receive(receiveBuffer);
string response = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived);
Console.WriteLine("Received: " + response);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
if (socket != null && socket.Connected)
{
// Close the socket and release resources.
socket.Close();
Console.WriteLine("Socket closed.");
}
}
Inheritance
- System.Object
- System.Net.Sockets.Socket