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 might 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
Socketclass 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[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[]) Method
Socket.ReceiveFrom(byte[], System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.Select Method
Socket.Send(byte[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[]) Method
Socket.Send(byte[], System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[], int, System.Net.Sockets.SocketFlags) Method
Socket.SendTo(byte[], System.Net.EndPoint) Method
Socket.SendTo(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) 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
Unknownmember 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 InvalidOperationException An asynchronous call is pending and a blocking method has been called.
SocketException An error occurred while accessing the listening socket or while creating the new socket. -or-
The System.Net.Sockets.Socket.Blocking property is set to
false.[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 will throw a SocketException. 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 accepting the connection. [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 making the connection. [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
trueto release both managed and unmanaged resources;falseto 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 LingerAn 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. SecurityException A caller in the call stack does not have the required permissions.
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 might 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-
Bindhas not been called on the current instance.-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 wheretrueindicates the current instance satisfies at least one of the conditions in the following table corresponding to the specified SelectMode value; otherwise,false.falseis 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. -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, buffer.Length, socketFlags).
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 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 c