public class Socket : IDisposable
Object
SocketThis type implements IDisposable.
System
Networking
Creates a communication endpoint through which an application sends or receives data across a network.
This class enables a Socket instance to communicate with another socket across a network. The communication can be through connection-oriented and connectionless protocols using either data streams or datagrams (discrete message packets).Message-oriented protocols preserve message boundaries and require that for each System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call there is one corresponding System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call. For stream-oriented protocols, data is transmitted without regards to message boundaries. In this case, for example, multiple System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method calls may be necessary to retrieve all the data from one System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call. The protocol is set in the
Socket
class constructor.A Socket instance has a local and a remote endpoint associated with it. The local endpoint contains the connection information for the current socket instance. The remote endpoint contains the connection information for the socket that the current instance communicates with. The endpoints are required to be an instance of a type derived from the EndPoint class. For the Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) protocols, an endpoint includes the address family, an Internet Protocol (IP) address, and a port number. For connection-oriented protocols (for example, TCP), the remote endpoint does not have to be specified when transferring data. For connectionless protocols (for example, UDP), the remote endpoint is required to be specified.
Methods are provided for both synchronous and asynchronous operations. A synchronous method can operate in blocking mode, in which it waits (blocks) until the operation is complete before returning, or in non-blocking mode, where it returns immediately, possibly before the operation has completed. The blocking mode is set through the System.Net.Sockets.Socket.Blocking property.
An asynchronous method returns immediately and, by convention, relies on a delegate to complete the operation. Asynchronous methods have names which correspond to their synchronous counterparts prefixed with either 'Begin' or End'. For example, the synchronous System.Net.Sockets.Socket.Accept method has asynchronous counterpart methods named System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) and System.Net.Sockets.Socket.EndAccept(System.IAsyncResult). The example for the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method shows the basic steps for using an asynchronous operation. A complete working example follows this discussion.
Connection-oriented protocols commonly use the client/server model. In this model, one of the sockets is set up as a server, and one or more sockets are set up as clients. A general procedure demonstrating the synchronous communication process for this model is as follows.
On the server-side:
On the client-side:
- Create a socket to listen for incoming connection requests.
- Set the local endpoint using the System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method.
- Put the socket in the listening state using the System.Net.Sockets.Socket.Listen(System.Int32) method.
- At this point incoming connection requests from a client are placed in a queue.
- Use the System.Net.Sockets.Socket.Accept method to create a server socket for a connection request issued by a client-side socket. This sets the remote endpoint.
- Use the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) methods to communicate with the client socket.
- When communication is finished, terminate the connection using the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.
- Release the resources allocated by the server socket using the System.Net.Sockets.Socket.Close method.
- Release the resources allocated by the listener socket using the System.Net.Sockets.Socket.Close method.
The shutdown step in the previous procedure is not necessary but ensures that any pending data is not lost. If the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method is not called, the System.Net.Sockets.Socket.Close method shuts down the connection either gracefully or by force. A graceful closure attempts to transfer all pending data before the connection is terminated. Use the System.Net.Sockets.SocketOptionName.Linger socket option to specify a graceful closure for a socket.
- Create the client socket.
- Connect to the server socket using the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method. This sets both the local and remote endpoints for the client socket.
- Use the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) methods to communicate with the server socket.
- > When communication is finished, terminate the connection using the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.
- Release the resources allocated by the client socket using the System.Net.Sockets.Socket.Close method.
[Note: This implementation is based on the UNIX sockets implementation in the Berkeley Software Distribution (BSD, release 4.3) from the University of California at Berkeley.
]
The following examples provide a client/server application that demonstrates the use of asynchronous communication between sockets. Run the client and server on different consoles.The following code is for the server application. Start this application before the client application.
using System; using System.Threading; using System.Text; using System.Net; using System.Net.Sockets; public class Server { // used to pass state information to delegate internal class StateObject { internal byte[] sBuffer; internal Socket sSocket; internal StateObject(int size, Socket sock) { sBuffer = new byte[size]; sSocket = sock; } } static void Main() { IPAddress ipAddress = Dns.Resolve( Dns.GetHostName() ).AddressList[0]; IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 1800); Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(ipEndpoint); listenSocket.Listen(1); IAsyncResult asyncAccept = listenSocket.BeginAccept( new AsyncCallback(Server.acceptCallback), listenSocket ); // could call listenSocket.EndAccept(asyncAccept) here // instead of in the callback method, but since // EndAccept blocks, the behavior would be similar to // calling the synchronous Accept method Console.Write("Connection in progress."); if( writeDot(asyncAccept) == true ) { // allow time for callbacks to // finish before the program ends Thread.Sleep(3000); } } public static void acceptCallback(IAsyncResult asyncAccept) { Socket listenSocket = (Socket)asyncAccept.AsyncState; Socket serverSocket = listenSocket.EndAccept(asyncAccept); // arriving here means the operation completed // (asyncAccept.IsCompleted = true) but not // necessarily successfully if( serverSocket.Connected == false ) { Console.WriteLine( ".server is not connected." ); return; } else Console.WriteLine( ".server is connected." ); listenSocket.Close(); StateObject stateObject = new StateObject(16, serverSocket); // this call passes the StateObject because it // needs to pass the buffer as well as the socket IAsyncResult asyncReceive = serverSocket.BeginReceive( stateObject.sBuffer, 0, stateObject.sBuffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), stateObject); Console.Write("Receiving data."); writeDot(asyncReceive); } public static void receiveCallback(IAsyncResult asyncReceive) { StateObject stateObject = (StateObject)asyncReceive.AsyncState; int bytesReceived = stateObject.sSocket.EndReceive(asyncReceive); Console.WriteLine( ".{0} bytes received: {1}", bytesReceived.ToString(), Encoding.ASCII.GetString(stateObject.sBuffer) ); byte[] sendBuffer = Encoding.ASCII.GetBytes("Goodbye"); IAsyncResult asyncSend = stateObject.sSocket.BeginSend( sendBuffer, 0, sendBuffer.Length, SocketFlags.None, new AsyncCallback(sendCallback), stateObject.sSocket); Console.Write("Sending response."); writeDot(asyncSend); } public static void sendCallback(IAsyncResult asyncSend) { Socket serverSocket = (Socket)asyncSend.AsyncState; int bytesSent = serverSocket.EndSend(asyncSend); Console.WriteLine( ".{0} bytes sent.{1}{1}Shutting down.", bytesSent.ToString(), Environment.NewLine ); serverSocket.Shutdown(SocketShutdown.Both); serverSocket.Close(); } // times out after 20 seconds but operation continues internal static bool writeDot(IAsyncResult ar) { int i = 0; while( ar.IsCompleted == false ) { if( i++ > 40 ) { Console.WriteLine("Timed out."); return false; } Console.Write("."); Thread.Sleep(500); } return true; } }The following code is for the client application. When starting the application, supply the hostname of the console running the server application as an input parameter (for example, ProgramName hostname ).
using System; using System.Threading; using System.Text; using System.Net; using System.Net.Sockets; public class Client { // used to pass state information to delegate class StateObject { internal byte[] sBuffer; internal Socket sSocket; internal StateObject(int size, Socket sock) { sBuffer = new byte[size]; sSocket = sock; } } static void Main(string[] argHostName) { IPAddress ipAddress = Dns.Resolve( argHostName[0] ).AddressList[0]; IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 1800); Socket clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult asyncConnect = clientSocket.BeginConnect( ipEndpoint, new AsyncCallback(connectCallback), clientSocket ); Console.Write("Connection in progress."); if( writeDot(asyncConnect) == true ) { // allow time for callbacks to // finish before the program ends Thread.Sleep(3000); } } public static void connectCallback(IAsyncResult asyncConnect) { Socket clientSocket = (Socket)asyncConnect.AsyncState; clientSocket.EndConnect(asyncConnect); // arriving here means the operation completed // (asyncConnect.IsCompleted = true) but not // necessarily successfully if( clientSocket.Connected == false ) { Console.WriteLine( ".client is not connected." ); return; } else Console.WriteLine( ".client is connected." ); byte[] sendBuffer = Encoding.ASCII.GetBytes("Hello"); IAsyncResult asyncSend = clientSocket.BeginSend( sendBuffer, 0, sendBuffer.Length, SocketFlags.None, new AsyncCallback(sendCallback), clientSocket); Console.Write("Sending data."); writeDot(asyncSend); } public static void sendCallback(IAsyncResult asyncSend) { Socket clientSocket = (Socket)asyncSend.AsyncState; int bytesSent = clientSocket.EndSend(asyncSend); Console.WriteLine( ".{0} bytes sent.", bytesSent.ToString() ); StateObject stateObject = new StateObject(16, clientSocket); // this call passes the StateObject because it // needs to pass the buffer as well as the socket IAsyncResult asyncReceive = clientSocket.BeginReceive( stateObject.sBuffer, 0, stateObject.sBuffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), stateObject); Console.Write("Receiving response."); writeDot(asyncReceive); } public static void receiveCallback(IAsyncResult asyncReceive) { StateObject stateObject = (StateObject)asyncReceive.AsyncState; int bytesReceived = stateObject.sSocket.EndReceive(asyncReceive); Console.WriteLine( ".{0} bytes received: {1}{2}{2}Shutting down.", bytesReceived.ToString(), Encoding.ASCII.GetString(stateObject.sBuffer), Environment.NewLine ); stateObject.sSocket.Shutdown(SocketShutdown.Both); stateObject.sSocket.Close(); } // times out after 2 seconds but operation continues internal static bool writeDot(IAsyncResult ar) { int i = 0; while( ar.IsCompleted == false ) { if( i++ > 20 ) { Console.WriteLine("Timed out."); return false; } Console.Write("."); Thread.Sleep(100); } return true; } }The output of the server application is
Connection in progress...........server is connected.
The output of the client application isReceiving data......5 bytes received: Hello
Sending response....7 bytes sent.
Shutting down.
-----------------------------------------
Connection in progress......client is connected.
Sending data......5 bytes sent.
Receiving response......7 bytes received: Goodbye
Shutting down.
System.Net.Sockets Namespace
Socket Constructors
Socket Methods
Socket.Accept Method
Socket.BeginAccept Method
Socket.BeginConnect Method
Socket.BeginReceive Method
Socket.BeginReceiveFrom Method
Socket.BeginSend Method
Socket.BeginSendTo Method
Socket.Bind Method
Socket.Close Method
Socket.Connect Method
Socket.Dispose Method
Socket.EndAccept Method
Socket.EndConnect Method
Socket.EndReceive Method
Socket.EndReceiveFrom Method
Socket.EndSend Method
Socket.EndSendTo Method
Socket.Finalize Method
Socket.GetHashCode Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName) Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method
Socket.IOControl Method
Socket.Listen Method
Socket.Poll Method
Socket.Receive(byte[], int, System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[], System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[]) Method
Socket.Receive(byte[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.ReceiveFrom(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], System.Net.EndPoint&) Method
Socket.Select Method
Socket.Send(byte[], int, System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[], System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[]) Method
Socket.Send(byte[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.SendTo(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], System.Net.EndPoint) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) Method
Socket.Shutdown Method
Socket.System.IDisposable.Dispose Method
Socket Properties
Socket.AddressFamily Property
Socket.Available Property
Socket.Blocking Property
Socket.Connected Property
Socket.Handle Property
Socket.LocalEndPoint Property
Socket.ProtocolType Property
Socket.RemoteEndPoint Property
Socket.SocketType Property
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);
Constructs and initializes a new instance of the Socket class.
- addressFamily
- One of the values defined in the AddressFamily enumeration.
- socketType
- One of the values defined in the SocketType enumeration.
- protocolType
- One of the values defined in the ProtocolType enumeration.
Exception Type Condition SocketException The combination of addressFamily, socketType, and protocolType is invalid. -or-
An error occurred while creating the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
The addressFamily parameter specifies the addressing scheme used by the current instance, the socketType parameter specifies the socket type of the current instance, and the protocolType parameter specifies the protocol used by the current instance. The three parameters are not independent. Some address families restrict which protocols are used, and often the socket type is determined by the protocol. When the specified values are not a valid combination, a SocketException exception is thrown.Using the
Unknown
member of either the AddressFamily or ProtocolType enumeration, results in a SocketException exception being thrown.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public Socket Accept();
Creates and initializes a new Socket instance and connects it to an incoming connection request.
A new connected Socket instance.
Exception Type Condition ArgumentException An error occurred while creating the new Socket. InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method is used only on the server-side of connection-oriented protocols. It extracts the first connection request from the queue of pending requests, creates a new Socket instance, and connects this instance to the socket associated with the request.The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when there are no pending connection requests. When
false
, this method returnsnull
. Whentrue
, this method blocks.The following properties of the new Socket instance returned by this method have values identical to the corresponding properties of the current instance:
The System.Net.Sockets.Socket.RemoteEndPoint property of the new instance is set to the local endpoint of the first request in the input queue. The System.Net.Sockets.Socket.Connected property is set to
- System.Net.Sockets.Socket.AddressFamily
- System.Net.Sockets.Socket.Blocking
- System.Net.Sockets.Socket.LocalEndPoint
- System.Net.Sockets.Socket.ProtocolType
- System.Net.Sockets.Socket.SocketType
true
.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginAccept(AsyncCallback callback, object state);
Begins an asynchronous operation to accept an incoming connection request.
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition SocketException An error occurred while starting the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method.
[Note: For more information, see System.Net.Sockets.Socket.Accept, the synchronous version of this method.
]
The following excerpt from the Socket class overview example outlines an asynchronous accept operation.
public class Server { static void Main() { . . . listenSocket.BeginAccept( new AsyncCallback(Server.acceptCallback), listenSocket); . . . // EndAccept can be called here . . . } public static void acceptCallback(IAsyncResult asyncAccept) { Socket listenSocket = (Socket)asyncAccept.AsyncState; Socket serverSocket = listenSocket.EndAccept(asyncAccept); serverSocket.BeginReceive(...); . . . } }
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state);
Begins an asynchronous operation to associate the current instance with a remote endpoint.
- remoteEP
- The EndPoint associated with the socket to connect to.
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition ArgumentNullException remoteEP is null
.
SocketException An error occurred while starting the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed. SecurityException A caller higher in the call stack does not have permission for the requested operation.
To release resources allocated by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method.
[Note: For more information, see System.Net.Sockets.Socket.Connect(System.Net.EndPoint), the synchronous version of this method.
]
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state);
Begins an asynchronous operation to receive data from a socket.
- buffer
- A Byte array to store data received from the socket.
- offset
- A Int32 containing the zero-based position in buffer to begin storing the received data.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
[Note: For more information, see System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method.
]
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state);
Begins an asynchronous operation to receive data from a socket and, for connectionless protocols, store the endpoint associated with the socket that sent the data.
- buffer
- A Byte array to store data received from the socket.
- offset
- A Int32 containing the zero-based position in buffer to begin storing the received data.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek .
- remoteEP
- An instance of a class derived from the EndPoint class, which contains the endpoint associated with the socket that sent the data.
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition ArgumentNullException buffer is null
.-or-
remoteEP is
null
.
ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed. SecurityException A caller in the call stack does not have the required permissions.
To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
[Note: For more information, see System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@), the synchronous version of this method.
]
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see Socket.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state);
Begins an asynchronous operation to send data to a connected socket.
- buffer
- A Byte array storing data to send to the socket.
- offset
- A Int32 containing the zero-based position in buffer containing the starting location of the data to send.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand .
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
[Note: For more information, see System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method.
]
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state);
Begins an asynchronous operation to send data to the socket associated with the specified endpoint.
- buffer
- A Byte array storing data to send to the socket.
- offset
- A Int32 containing the zero-based position in buffer to begin sending data.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand .
- remoteEP
- The EndPoint associated with the socket to receive the data.
- callback
- A AsyncCallback delegate, or
null
.- state
- An application-defined object, or
null
.
A IAsyncResult instance that contains information about the asynchronous operation.
Exception Type Condition ArgumentNullException buffer is null
.-or-
remoteEP is
null
.
ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed. SecurityException A caller in the call stack does not have the required permissions.
To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.[Note: The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method.]
If the callback parameter is not
null
, the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method.The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.
[Note: For more information, see System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), the synchronous version of this method.
]
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void Bind(EndPoint localEP);
Associates the current instance with a local endpoint.
- localEP
- The local EndPoint to be associated with the socket.
Exception Type Condition ArgumentNullException localEP is null
.SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed. SecurityException A caller in the call stack does not have the required permission.
This method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to localEP.[Note: For connection-oriented protocols, this method is generally used only on the server-side and is required to be called before the first call to the System.Net.Sockets.Socket.Listen(System.Int32) method. On the client-side, binding is usually performed implicitly by the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method.
For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint)System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), and System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) methods bind the current instance to the local endpoint if the current instance has not previously been bound.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void Close();
Closes the current instance and releases all managed and unmanaged resources allocated by the current instance.
This method calls the System.Net.Sockets.Socket.Dispose(System.Boolean)(Boolean) method with the argument set totrue
, which frees both managed and unmanaged resources used by the current instance.The socket attempts to perform a graceful closure when the System.Net.Sockets.SocketOptionName.Linger socket option is enabled and set to a non-zero linger time. In all other cases, closure is forced and any pending data is lost.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void Connect(EndPoint remoteEP);
Associates the current instance with a remote endpoint.
- remoteEP
- The EndPoint associated with the socket to connect to.
Exception Type Condition ArgumentNullException remoteEP is null
.InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed. SecurityException A caller in the call stack does not have the required permission.
This method sets the System.Net.Sockets.Socket.RemoteEndPoint property of the current instance to remoteEP.[Note: For connection-oriented protocols, this method establishes a connection between the current instance and the socket associated with remoteEP. This method is used only on the client-side. The System.Net.Sockets.Socket.Accept method establishes the connection on the server-side. Once the connection has been made, data can be sent using the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method, and received using the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method.
For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method can be used from both client and server-sides, allowing the use of the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. The System.Net.Sockets.Socket.RemoteEndPoint property is set to remoteEP and the System.Net.Sockets.Socket.LocalEndPoint property is set to a value determined by the protocol; however, a connection is not established. Subsequent data is required to be received on the endpoint set in the System.Net.Sockets.Socket.LocalEndPoint property.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
protected virtual void Dispose(bool disposing);
Closes the current instance, releases the unmanaged resources allocated by the current instance, and optionally releases the managed resources.
- disposing
- A Boolean. Specify
true
to release both managed and unmanaged resources;false
to release only unmanaged resources.
[Behaviors: This method closes the current Socket instance and releases all unmanaged resources allocated by the current instance. When disposing istrue
, this method also releases all resources held by any managed objects allocated by the current instance. ]
[Default: This method closes the current Socket instance but does not release any managed resources. ]
[Overrides: The System.Net.Sockets.Socket.Dispose(System.Boolean) method can be called multiple times by other objects. When overriding this method, do not reference objects that have been previously disposed in an earlier call. ]
[Usage: Use this method to release resources allocated by the current instance. ]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public Socket EndAccept(IAsyncResult asyncResult);
Ends an asynchronous call to accept an incoming connection request.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
A new connected Socket instance.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. InvalidOperationException System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void EndConnect(IAsyncResult asyncResult);
Ends an asynchronous call to associate the current instance with a remote endpoint.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. InvalidOperationException System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int EndReceive(IAsyncResult asyncResult);
Ends an asynchronous call to receive data from a socket.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. InvalidOperationException System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint);
Ends an asynchronous call to receive data from a socket and store the endpoint associated with the socket that sent the data.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
- endPoint
- A reference to the EndPoint associated with the socket that sent the data.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. InvalidOperationException System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int EndSend(IAsyncResult asyncResult);
Ends an asynchronous call to send data to a connected socket.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. InvalidOperationException System.Net.Sockets.Socket.EndSend(System.IAsyncResult) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int EndSendTo(IAsyncResult asyncResult);
Ends an asynchronous call to send data to a socket associated with a specified endpoint.
- asyncResult
- A IAsyncResult object that holds the state information for the asynchronous operation.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException asyncResult is null
.ArgumentException asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. InvalidOperationException System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) was previously called for this operation. SocketException An error occurred during the operation. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method blocks if the asynchronous operation has not completed.The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request.
If the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.
For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
~Socket();
Closes the current instance and releases unmanaged resources allocated by the current instance.
[Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize(System.Object), and System.Object.Finalize.This method calls System.Net.Sockets.NetworkStream.Dispose(System.Boolean)(
false
) to free unmanaged resources used by the current instance.This method overrides System.Object.Finalize.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public override int GetHashCode();
Generates a hash code for the current instance.
A Int32 containing the hash code for the current instance.
The algorithm used to generate the hash code is unspecified.[Note: This method overrides System.Object.GetHashCode. ]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName);
Retrieves an object containing the value of the specified socket option.
- optionLevel
- One of the values defined in the SocketOptionLevel enumeration.
- optionName
- One of the values defined in the SocketOptionName enumeration.
The following table describes the values returned by this method.
optionName Return value Linger
An instance of the LingerOption class. AddMembership
-or-
DropMembership
An instance of the MulticastOption class. All other values defined in the SocketOptionName enumeration. A Int32 containing the value of the option.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance.optionLevel and optionName are not independent. See the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(
SocketOptionLevel
,SocketOptionName
,Int32
) method for a listing of the values of the SocketOptionName enumeration grouped by SocketOptionLevel.
The following example gets the state of the linger option and the size of the receive buffer, changes the values of both, then gets the new values.
using System; using System.Net.Sockets; class OptionTest{ public static void Main() { // Get the current option values. Socket someSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); LingerOption lingerOp = (LingerOption)someSocket.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger); int receiveBuffer = (int)someSocket.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); Console.WriteLine( "Linger option is {0} and set to {1} seconds.", lingerOp.Enabled.ToString(), lingerOp.LingerTime.ToString() ); Console.WriteLine( "Size of the receive buffer is {0} bytes.", receiveBuffer.ToString() ); // Change the options. lingerOp = new LingerOption(true, 10); someSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOp); someSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 2048); Console.WriteLine( "The SetSocketOption method has been called."); // Get the new option values. lingerOp = (LingerOption)someSocket.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger); receiveBuffer = (int)someSocket.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); Console.WriteLine( "Linger option is now {0} and set to {1} seconds.", lingerOp.Enabled.ToString(), lingerOp.LingerTime.ToString()); Console.WriteLine( "Size of the receive buffer is now {0} bytes.", receiveBuffer.ToString()); } }The output is
Linger option is False and set to 0 seconds.
Size of the receive buffer is 8192 bytes.
The SetSocketOption method has been called.
Linger option is now True and set to 10 seconds.
Size of the receive buffer is now 2048 bytes.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue);
Retrieves the value of the specified socket option.
- optionLevel
- One of the values defined in the SocketOptionLevel enumeration.
- optionName
- One of the values defined in the SocketOptionName enumeration.
- optionValue
- A Byte array that receives the value of the specified socket option.
Exception Type Condition SocketException optionValue is too small to store the value of the specified socket option. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance.Upon successful completion, the array specified by the optionValue parameter contains the value of the specified socket option.
When the length of the optionValue array is smaller than the number of bytes required to store the value of the specified socket option, a SocketException exception is thrown.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength);
Retrieves the value of the specified socket option.
- optionLevel
- One of the values defined in the SocketOptionLevel enumeration.
- optionName
- One of the values defined in the SocketOptionName enumeration.
- optionLength
- A Int32 containing the maximum length, in bytes, of the value of the specified socket option.
A Byte array containing the value of the specified socket option.
Exception Type Condition SocketException optionLength is smaller than the number of bytes required to store the value of the specified socket option. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance.The optionLength parameter is used to allocate an array to store the value of the specified option. When this value is smaller than the number of bytes required to store the value of the specified option, a SocketException exception is thrown. When this value is greater than or equal to the number of bytes required to store the value of the specified option, the array returned by this method is allocated to be exactly the required length.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue);
Provides low-level access to the socket, the transport protocol, or the communications subsystem.
- ioControlCode
- A Int32 containing the control code of the operation to perform.
- optionInValue
- A Byte array containing the input data required by the operation.
- optionOutValue
- A Byte array containing the output data supplied by the operation.
A Int32 containing the length of the optionOutValue array after the method returns.
Exception Type Condition InvalidOperationException An attempt was made to change the blocking mode. [Note: Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode.
]
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
If an attempt is made to change the blocking mode of the current instance, an exception is thrown. Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode.The control codes and their requirements are implementation defined. Do not use this method if platform independence is a requirement.
[Note: Input data is not required for all control codes. Output data is not supplied by all control codes and, if not supplied, the return value is 0. ]
The following example gets the number of bytes of available data to be read and writes the result to the console on a Windows system. The remote endpoint (remoteEndpoint) to connect to may need to be changed to a value that is valid on the current system.
using System; using System.Net; using System.Net.Sockets; class App { static void Main() { IPAddress remoteAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0]; IPEndPoint remoteEndpoint = new IPEndPoint(remoteAddress, 80); Socket someSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); someSocket.Connect(remoteEndpoint); int fionRead = 0x4004667F; byte[]inValue = {0x00, 0x00, 0x00, 0x00}; byte[]outValue = {0x00, 0x00, 0x00, 0x00}; someSocket.IOControl(fionRead, inValue, outValue); uint bytesAvail = BitConverter.ToUInt32(outValue, 0); Console.WriteLine( "There are {0} bytes available to be read.", bytesAvail.ToString() ); } }The output is
There are 0 bytes available to be read.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void Listen(int backlog);
Places the current instance into the listening state where it waits for incoming connection requests.
- backlog
- A Int32 containing the maximum length of the queue of pending connections.
Exception Type Condition SocketException The System.Net.Sockets.Socket.Connected property of the current instance is true, or an error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
Once this method is called, incoming connection requests are placed in a queue. The maximum size of the queue is specified by the backlog parameter. The size of the queue is limited to legal values by the underlying protocol. Illegal values of the backlog parameter are replaced with a legal value, which is implementation defined.If a connection request arrives and the queue is full, a SocketException is thrown on the client.
A socket in the listening state has no remote endpoint associated with it. Attempting to access the System.Net.Sockets.Socket.RemoteEndPoint property throws a SocketException exception.
This method is ignored if called more than once on the current instance.
[Note: This method is used only on the server-side of connection-oriented protocols. Call the System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method before this method is called the first time. Call the System.Net.Sockets.Socket.Listen(System.Int32) method before the first call to the System.Net.Sockets.Socket.Accept method.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public bool Poll(int microSeconds, SelectMode mode);
Determines the read, write, or error status of the current instance.
- microSeconds
- A Int32 containing the time to wait for a response, in microseconds. Set the microSeconds parameter to a negative value to wait indefinitely for a response.
- mode
- One of the values defined in the SelectMode enumeration.
A Boolean wheretrue
indicates the current instance satisfies at least one of the conditions in the following table corresponding to the specified SelectMode value; otherwise,false
.false
is returned if the status of the current instance cannot be determined within the time specified by microSeconds .
SelectMode value Condition SelectRead Data is available for reading (includes out-of-band data if the System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is set). -or-
The socket is in the listening state with a pending connection, and the System.Net.Sockets.Socket.Accept method has been called and is guaranteed to succeed without blocking.
-or-
The connection has been closed, reset, or terminated.
SelectWrite Data can be sent. -or-
A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has succeeded.
SelectError The System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is not set and out-of-band data is available. -or-
A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has failed.
Exception Type Condition NotSupportedException mode is not one of the values defined in the SelectMode enumeration. SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Receive(byte[] buffer, int size, SocketFlags socketFlags);
Receives data from a socket.
- buffer
- A Byte array to store data received from the socket.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException size < 0. -or-
size > buffer.Length.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Receive(byte[] buffer, SocketFlags socketFlags);
Receives data from a socket.
- buffer
- A Byte array to store data received from the socket.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer is null
.InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values.
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Receive(byte[] buffer);
Receives data from a socket.
- buffer
- A Byte array to store data received from the socket.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer is null
.InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags);
Receives data from a socket.
- buffer
- A Byte array to store data received from the socket.
- offset
- A Int32 containing the zero-based position in buffer to begin storing the received data.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
The System.Net.Sockets.Socket.LocalEndPoint property was not set.
-or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called.The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When
false
, the SocketException exception is thrown. Whentrue
, this method blocks and waits for data to arrive.For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state.
For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider.
When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned.
When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP);
Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.
- buffer
- A Byte array to store data received from the socket.
- offset
- A Int32 containing the zero-based position in buffer to begin storing the received data.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
- remoteEP
- A reference to the EndPoint associated with the socket that sent the data.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
The System.Net.Sockets.Socket.LocalEndPoint property was not set.
-or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
For connectionless protocols, when this method successfully completes, remoteEP contains the endpoint associated with the socket that sent the data.For connection-oriented protocols, remoteEP is left unchanged.
The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called or a SocketException is thrown.
The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When
false
, the SocketException exception is thrown. Whentrue
, this method blocks and waits for data to arrive.For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state.
For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider.
When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of thesocketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned.
When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP);
Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.
- buffer
- A Byte array to store data received from the socket.
- size
- A Int32 containing the number of bytes to receive.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
- remoteEP
- A reference to the EndPoint associated with the socket that sent the data.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
ArgumentOutOfRangeException size < 0. -or-
size > buffer.Length.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, size , socketFlags, remoteEP ).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP);
Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.
- buffer
- A Byte array to store data received from the socket.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
- remoteEP
- A reference to the EndPoint associated with the socket that sent the data.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags specified an invalid value. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, socketFlags, remoteEP).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP);
Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.
- buffer
- A Byte array to store data received from the socket.
- remoteEP
- A reference to the EndPoint associated with the socket that sent the data.
A Int32 containing the number of bytes received.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds);
Determines the read, write, or error status of a set of Socket instances.
- checkRead
- A IList object containing the Socket instances to check for read status.
- checkWrite
- A IList object containing the Socket instances to check for write status.
- checkError
- A IList object containing the Socket instances to check for error status.
- microSeconds
- A Int32 that specifies the time to wait for a response, in microseconds. Specify a negative value to wait indefinitely for the status to be determined.
Exception Type Condition ArgumentNullException All of the following parameters are null
or empty: checkRead, checkWrite, and checkError.SocketException An error occurred while accessing one of the sockets. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
Upon successful completion, this method removes all Socket instances from the specified list that do not satisfy one of the conditions associated with that list. The following table describes the conditions for each list.
[Note: To determine the status of a specific Socket instance, check whether the instance remains in the list after the method returns.]
List Condition to remain in list checkRead Data is available for reading (includes out-of-band data if the System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is set). -or-
The socket is in the listening state with a pending connection, and the System.Net.Sockets.Socket.Accept method has been called and is guaranteed to succeed without blocking.
-or-
The connection has been closed, reset, or terminated.
checkWrite Data can be sent. -or-
A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has succeeded.
checkError The System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is not set and out-of-band data is available. -or-
A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has failed.
When the method cannot determine the status of all the Socket instances within the time specified in the microseconds parameter, the method removes all the Socket instances from all the lists and returns.
At least one of checkRead, checkWrite, or checkError, is required to contain at least one Socket instance. The other parameters can be empty or
null
.
The following example determines the status of the socket instance named socket3 and writes the result to the console.
using System; using System.Collections; using System.Net.Sockets; class SelectTest { public static void Main() { Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket socket3 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ArrayList readList = new ArrayList(); ArrayList writeList = new ArrayList(); ArrayList errorList = new ArrayList(); readList.Add(socket1); readList.Add(socket2); readList.Add(socket3); errorList.Add(socket1); errorList.Add(socket3); // readList.Contains(Socket3) returns true // if Socket3 is in ReadList. Console.WriteLine( "socket3 is placed in readList and errorList."); Console.WriteLine( "socket3 is {0}in readList.", readList.Contains(socket3) ? "" : "not " ); Console.WriteLine( "socket3 is {0}in writeList.", writeList.Contains(socket3) ? "" : "not " ); Console.WriteLine( "socket3 is {0}in errorList.", errorList.Contains(socket3) ? "" : "not " ); Socket.Select(readList, writeList, errorList, 10); Console.WriteLine("The Select method has been called."); Console.WriteLine( "socket3 is {0}in readList.", readList.Contains(socket3) ? "" : "not " ); Console.WriteLine( "socket3 is {0}in writeList.", writeList.Contains(socket3) ? "" : "not " ); Console.WriteLine( "socket3 is {0}in errorList.", errorList.Contains(socket3) ? "" : "not " ); } }The output is
socket3 is placed in readList and errorList.
socket3 is in readList.
socket3 is not in writeList.
socket3 is in errorList.
The Select method has been called.
socket3 is not in readList.
socket3 is not in writeList.
socket3 is not in errorList.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Send(byte[] buffer, int size, SocketFlags socketFlags);
Sends data to a connected socket.
- buffer
- A Byte array containing data to send to the socket.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException size < 0. -or-
size > buffer.Length.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Send(byte[] buffer, SocketFlags socketFlags);
Sends data to a connected socket.
- buffer
- A Byte array containing data to send to the socket.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer is null
.InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Send(byte[] buffer);
Sends data to a connected socket.
- buffer
- A Byte array containing data to send to the socket.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer is null
.InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags);
Sends data to a connected socket.
- buffer
- A Byte array containing data to send to the socket.
- offset
- A Int32 that specifies the zero-based position in buffer that is the starting location of the data to send.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer is null
.ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
For connection-oriented protocols, the System.Net.Sockets.Socket.LocalEndPoint property of the current instance is required to be set before calling this method.For connectionless protocols, calling the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods sets the System.Net.Sockets.Socket.RemoteEndPoint property and allows the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method to be used instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method.
When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed.
When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent.
When the System.Net.Sockets.Socket.Blocking property of the current instance is set to
true
and buffer space is not available within the underlying protocol, this method blocks.For message-oriented sockets, when the size of buffer is greater than the maximum message size of the underlying protocol, no data is sent and the SocketException exception is thrown.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP);
Sends data to the socket associated with the specified endpoint.
- buffer
- A Byte array containing data to send to the socket.
- offset
- A Int32 that specifies the zero-based position in buffer that is the starting location of the data to send.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
- remoteEP
- The EndPoint associated with the socket to receive the data.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
ArgumentOutOfRangeException offset < 0. -or-
offset > buffer.Length.
-or-
size < 0.
-or-
size > buffer.Length - offset.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
For connection-oriented protocols and connected sockets using connectionless protocols, remoteEP overrides the endpoint specified in the System.Net.Sockets.Socket.RemoteEndPoint property.For unconnected sockets using connectionless protocols, this method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to a value determined by the protocol. Subsequent data is required to be received on
LocalEndPoint
.When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed.
When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent.
When the System.Net.Sockets.Socket.Blocking property of the current instance is set to
true
and buffer space is not available within the underlying protocol, this method blocks.For message-oriented sockets, when the size of buffer is greater than the maximum message size of the underlying protocol, no data is sent and the SocketException exception is thrown.
For connection-oriented sockets, the remoteEP property is ignored.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP);
Sends data to the socket associated with the specified endpoint.
- buffer
- A Byte array containing data to send to the socket.
- size
- A Int32 containing the number of bytes to send.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
- remoteEP
- The EndPoint associated with the socket to receive the data.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
ArgumentOutOfRangeException size < 0. -or-
size > buffer.Length.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, size, socketFlags, remoteEP).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP);
Sends data to the socket associated with the specified endpoint.
- buffer
- A Byte array containing data to send to the socket.
- socketFlags
- A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
- remoteEP
- The EndPoint associated with the socket to receive the data.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException socketFlags is not a valid combination of values. -or-
An error occurred while accessing the socket.
[Note: For additional information on causes of the
SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, socketFlags, remoteEP).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int SendTo(byte[] buffer, EndPoint remoteEP);
Sends data to the socket associated with the specified endpoint.
- buffer
- A Byte array containing data to send to the socket.
- remoteEP
- The EndPoint associated with the socket to receive the data.
A Int32 containing the number of bytes sent.
Exception Type Condition ArgumentNullException buffer or remoteEP is null
.
InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP).
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue);
Sets socket options with values of type Int32 and Boolean.
- optionLevel
- One of the values defined in the SocketOptionLevel enumeration.
- optionName
- One of the values defined in the SocketOptionName enumeration.
- optionValue
- A Int32 containing the value of the option.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.For a socket option with a Boolean data type, specify a non-zero optionValue to enable the option, and an optionValue equal to zero to disable the option.
Socket options are grouped by level of protocol support. The following tables list the members of the SocketOptionName enumeration supported by each member of the SocketOptionLevel enumeration. Only members that have associated values of the Int32 and Boolean data types are listed.
The following table lists the members of the SocketOptionName enumeration supported by the
Socket
member of the SocketOptionLevel enumeration. Options that do not require permission to access unmanaged code are noted.The following table lists the members of the SocketOptionName enumeration supported by the
SocketOptionName Description Broadcast A Boolean where true
indicates broadcast messages are allowed to be sent to the socket.Debug A Boolean where true
indicates to record debugging information.DontLinger A Boolean where true
indicates to close the socket without lingering. This option does not require permission to access unmanaged code.DontRoute A Boolean where true
indicates not to route data.Error A Int32 that contains the error code associated with the last socket error. The error code is cleared by this option. This option is read-only. KeepAlive A Boolean where true
(the default) indicates to enable keep-alives, which allows a connection to remain open after a request has completed. This option does not require permission to access unmanaged code.OutOfBandInline A Boolean where true
indicates to receive out-of-band data in the normal data stream.ReceiveBuffer A Int32 that specifies the total per-socket buffer space reserved for receives. This option does not require permission to access unmanaged code. ReceiveTimeout A Int32 that specifies the maximum time, in milliseconds, the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@) methods will block when attempting to receive data. If data is not received within this time, a SocketException exception is thrown. This option does not require permission to access unmanaged code. ReuseAddress A Boolean where true
allows the socket to be bound to an address that is already in use.SendBuffer A Int32 that specifies the total per-socket buffer space reserved for sends. This option does not require permission to access unmanaged code. SendTimeout A Int32 that specifies the maximum time, in milliseconds, the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) methods will block when attempting to send data. If data is not sent within this time, a SocketException exception is thrown. This option does not require permission to access unmanaged code. Type One of the values defined in the SocketType enumeration. This option is read-only.
IP
member of the SocketOptionLevel enumeration. These options require permission to access unmanaged code.
SocketOptionName Description HeaderIncluded A Boolean where true
indicates the application is providing the IP header for outgoing datagrams.IPOptions A Byte array that specifies IP options to be inserted into outgoing datagrams. IpTimeToLive A Int32 that specifies the time-to-live for datagrams. The time-to-live designates the number of networks on which the datagram is allowed to travel before being discarded by a router. MulticastInterface A Byte array that specifies the interface for outgoing multicast packets. MulticastLoopback A Boolean where true
enables multicast loopback.MulticastTimeToLive A Int32 that specifies the time-to-live for multicast datagrams. TypeOfService A Int32 that specifies the type of service field in the IP header. UseLoopback A Boolean where true
indicates to send a copy of the data back to the sender.The following table lists the members of the SocketOptionName enumeration supported by the
Tcp
member of the SocketOptionLevel enumeration. These options do not require permission to access unmanaged code.
SocketOptionName Description BsdUrgent A Boolean where true
indicates to use urgent data as defined by IETF RFC 1222. Once enabled, this option cannot be disabled.Expedited A Boolean where true
indicates to use expedited data as defined by IETF RFC 1222. Once enabled, this option cannot be disabled.NoDelay A Boolean where true
indicates to disable the Nagle algorithm for send coalescing.The following table lists the members of the SocketOptionName enumeration supported by the
Udp
member of the SocketOptionLevel enumeration. These options do not require permission to access unmanaged code.
SocketOptionName Description ChecksumCoverage A Boolean that specifies UDP checksum coverage. NoChecksum A Boolean where true
indicates to send UDP datagrams with the checksum set to zero.[Note: For the
AddMembership
,DropMembership
, andLinger
members of the SocketOptionName enumeration, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Object) version of this method.]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue);
Sets socket options with values of typeByte[]
.
- optionLevel
- One of the values defined in the SocketOptionLevel enumeration.
- optionName
- One of the values defined in the SocketOptionName enumeration.
- optionValue
- A Byte array containing the value of the option.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.[Note: For socket options with values of type Int32 or Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName , Int32) version of this method.]
[Note: For the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Object) version of this method.]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue);
Sets the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options.
- optionLevel
- Either the
Socket
orIP
member of the SocketOptionLevel enumeration.- optionName
- Either the
Linger
,AddMembership
, orDropMembership
member of the SocketOptionName enumeration.- optionValue
- An instance of the LingerOption or MulticastOption class.
Exception Type Condition ArgumentException optionLevel, optionName, or optionValue specified an invalid value. ArgumentNullException optionValue is null
.SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
SecurityException A caller in the call stack does not have the required permissions. ObjectDisposedException The current instance has been disposed.
Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.The following table summarizes the valid combinations of input parameters.
When setting the System.Net.Sockets.SocketOptionName.Linger option, a ArgumentException exception is thrown if the System.Net.Sockets.LingerOption.LingerTime property of the LingerOption instance is less than zero or greater than System.UInt16.MaxValue .
optionLevel/optionName optionValue Socket
/Linger
An instance of the LingerOption class. IP
/AddMembership
- or -
IP
/DropMembership
An instance of the MulticastOption class. [Note: For more information on the System.Net.Sockets.SocketOptionName.Linger option, see the LingerOption class and the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.
For more information on the System.Net.Sockets.SocketOptionName.AddMembership and System.Net.Sockets.SocketOptionName.DropMembership options, see the MulticastOption class.
For socket options with values of type Int32 or Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Int32) version of this method.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public void Shutdown(SocketShutdown how);
Terminates the ability to send or receive data on a connected socket.
- how
- One of the values defined in the SocketShutdown enumeration.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
When how is set to System.Net.Sockets.SocketShutdown.Send , the socket on the other end of the connection is notified that the current instance will not send any more data. If the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method is subsequently called, a SocketException exception is thrown.When how is set to System.Net.Sockets.SocketShutdown.Receive, the socket on the other end of the connection is notified that the current instance will not receive any more data. After all the data currently queued on the current instance is received, any subsequent calls to the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method cause a SocketException exception to be thrown.
Setting how to System.Net.Sockets.SocketShutdown.Both terminates both sends and receives as described above. Once this occurs, the socket cannot be used.
[Note: To free resources allocated by the current instance, call the System.Net.Sockets.Socket.Close method.
Expected common usage is for the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method to be called before the System.Net.Sockets.Socket.Close method to ensure that all pending data is sent or received.
]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
void IDisposable.Dispose();
Implemented to support the IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public AddressFamily AddressFamily { get; }
Gets the address family of the current instance.
One of the values defined in the AddressFamily enumeration.
This property is read-only.This property is set by the constructor for the current instance. The value of this property specifies the addressing scheme used by the current instance to resolve an address.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public int Available { get; }
Gets the amount of data available to be read in a single System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) or System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@) call.
A Int32 containing the number of bytes of data that are available to be read.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This property is read-only.When the current instance is stream-oriented (for example, the System.Net.Sockets.SocketType.Stream socket type), the available data is generally the total amount of data queued on the current instance.
When the current instance is message-oriented (for example, the System.Net.Sockets.SocketType.Dgram socket type), the available data is the first message in the input queue.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public bool Blocking { get; set; }
Gets or sets a Boolean value that indicates whether the socket is in blocking mode.
true
indicates that the current instance is in blocking mode;false
indicates that the current instance is in non-blocking mode.
Exception Type Condition ObjectDisposedException The current instance has been disposed.
Blocking is when a method waits to complete an operation before returning. Sockets are created in blocking mode by default.Except for when the current instance has been disposed, no notification is given when an attempt to change the value of this property fails.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public bool Connected { get; }
Gets a Boolean value indicating whether the current instance is connected.
true
indicates that the current instance was connected at the time of the last I/O operation;false
indicates that the current instance is not connected.
This property is read-only.When this property returns
true
, the current instance was connected at the time of the last I/O operation; it might not still be connected. When this property returnsfalse
, the current instance was never connected or is not currently connected.The current instance is considered connected when the System.Net.Sockets.Socket.RemoteEndPoint property contains a valid endpoint.
[Note: The System.Net.Sockets.Socket.Accept and System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods, and their asynchronous counterparts set this property.]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public IntPtr Handle { get; }
Gets the operating system handle for the current instance.
A IntPtr containing the operating system handle for the current instance.
This property is read-only.
RuntimeInfrastructure
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public EndPoint LocalEndPoint { get; }
Gets the local endpoint associated with the current instance.
The local EndPoint associated with the current instance.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This property is read-only.This property contains the network connection information for the current instance.
[Note: The System.Net.Sockets.Socket.Bind(System.Net.EndPoint) and System.Net.Sockets.Socket.Accept methods, and their asynchronous counterparts set this property. If not previously set, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) and System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) methods, and their asynchronous counterparts set this property. ]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public ProtocolType ProtocolType { get; }
Gets the protocol type of the current instance.
One of the values defined in the ProtocolType enumeration.
This property is read-only.This property is set by the constructor for the current instance. The value of this property specifies the protocol used by the current instance.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public EndPoint RemoteEndPoint { get; }
Gets the remote endpoint associated with the current instance.
The remote EndPoint associated with the current instance.
Exception Type Condition SocketException An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException
, see the SocketException class.]
ObjectDisposedException The current instance has been disposed.
This property is read-only.This property contains the network connection information associated with the socket communicating with the current instance.
There is no remote endpoint associated with a socket in the listening state. An attempt to access the System.Net.Sockets.Socket.RemoteEndPoint property causes a SocketException exception to be thrown.
[Note: The System.Net.Sockets.Socket.Accept and System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods, and their asynchronous counterparts set this property. ]
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace
public SocketType SocketType { get; }
Gets the socket type of the current instance.
One of the values defined in the SocketType enumeration.
This property is read-only.This property is set by the constructor for the current instance.
System.Net.Sockets.Socket Class, System.Net.Sockets Namespace