Type: System.Net.Sockets.Socket System.Net.Sockets.Socket ClassAssembly: System.dll Namespace: System.Net.Sockets Summary Implements the Berkeley sockets interface. C# Syntax: public class Socket : IDisposable Remarks The Socket class creates a managed version of an Internet transport service. Once the Socket is created, the Socket is bound to a specific endpoint through the Socket.Bind method, and the connection to that endpoint is established through the Socket.Connect method. Data is sent to the Socket using the Socket.Send or Socket.SendTo methods, and data is read from the Socket using the Socket.Receive or Socket.ReceiveFrom methods. After you are done with the Socket, use the Socket.Shutdown method to disable the Socket, and the Socket.Close method to close the Socket. The Socket class is used by the Microsoft .NET Framework to provide Internet connections to the TcpClient, UdpClient, and WebRequest and descendent classes. Example The following example shows how the Socket class can be used to send data to an HTTP server and receive the response.
public string DoSocketGet(string server)
{
//Sets up variables and a string to write to the server
Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;
// IPAddress and IPEndPoint represent the endpoint that will
// receive the request.
// Get the first IPAddress in the list using DNS.
IPAddress hostadd = Dns.Resolve(server).AddressList[0];
IPEndPoint EPhost = new IPEndPoint(hostadd, 80);
//Creates the Socket for sending data over TCP.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp );
// Connects to the host using IPEndPoint.
s.Connect(EPhost);
if (!s.Connected)
{
strRetPage = "Unable to connect to host";
return strRetPage;
}
// Sends the GET text to the host.
s.Send(ByteGet, ByteGet.Length, SocketFlags.None);
// Receives the page, looping until all bytes are received
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = "Default HTML page on " + server + ":\r\n";
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, SocketFlags.None);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}
return strRetPage;
}
See also: System.Net.Sockets Namespace System.Net.Sockets.Socket Member List: Public Constructors ctor #1 Initializes a new instance of the Socket class. Public Properties AddressFamily Read-only Gets the address family of the Socket. Available Read-only Gets the amount of data that has been received from the network and is available to be read. Blocking Read-write Gets or sets a value that indicates whether the Socket is in blocking mode. Connected Read-only Gets a value indicating whether a Socket is connected to a remote resource. Handle Read-only Gets the operating system handle for the Socket. LocalEndPoint Read-only Gets the local endpoint. ProtocolType Read-only Gets the protocol type of the Socket. RemoteEndPoint Read-only Gets the remote endpoint. SocketType Read-only Gets the type of the Socket. Public Methods Accept Creates a new Socket to handle an incoming connection request. BeginAccept Begins an asynchronous request to create a new Socket to accept an incoming connection request. BeginConnect Begins an asynchronous request for a connection to a network device. BeginReceive Begins to asynchronously receive data from a connected Socket. BeginReceiveFrom Begins to asynchronously receive data from a specified network device. BeginSend Sends data asynchronously to a connected Socket. BeginSendTo Sends data asynchronously to a specific remote host. Bind Associates a Socket with a local endpoint. Close Forces a Socket connection to close. Connect Establishes a connection to a remote device. EndAccept Ends an asynchronous request to create a new Socket to accept an incoming connection request. EndConnect Ends a pending asynchronous connection request. EndReceive Ends a pending asynchronous read. EndReceiveFrom Ends a pending asynchronous read from a specific endpoint. EndSend Ends a pending asynchronous send. EndSendTo Ends a pending asynchronous send to a specific location. Equals (inherited from System.Object) See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. GetHashCode Overridden: GetSocketOption Overloaded: GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) Gets the value of a specified socket option. GetSocketOption Overloaded: GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) Gets the specified Socket option setting. GetSocketOption Overloaded: GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength) Returns the value of the specified Socket option and returns in an array. GetType (inherited from System.Object) See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. IOControl Sets low-level operating modes for the Socket. Listen Places a Socket in a listening state. Poll Determines the status of the Socket. Receive Overloaded: Receive(byte[] buffer) Receives data from a connected Socket into a specific location of the receive buffer. Receive Overloaded: Receive(byte[] buffer, SocketFlags socketFlags) Receives data from a connected Socket into a specific location of the receive buffer. Receive Overloaded: Receive(byte[] buffer, int size, SocketFlags socketFlags) Receives data from a connected Socket into a specific location of the receive buffer. Receive Overloaded: Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags) Receives data from a connected Socket in a specific location of the receive buffer. ReceiveFrom Overloaded: ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) Receives a datagram in a specific location in the data buffer and stores the endpoint. ReceiveFrom Overloaded: ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) Receives a datagram in a specific location in the data buffer and stores the endpoint. ReceiveFrom Overloaded: ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP) Receives a datagram in a specific location in the data buffer and stores the endpoint. ReceiveFrom Overloaded: ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) Receives a datagram in a specific location in the data buffer and stores the endpoint. Select Determines the status of one or more sockets. Send Overloaded: Send(byte[] buffer) Sends data to a connected Socket, starting at the indicated location in the data. Send Overloaded: Send(byte[] buffer, SocketFlags socketFlags) Sends data to a connected Socket, starting at the indicated location in the data. Send Overloaded: Send(byte[] buffer, int size, SocketFlags socketFlags) Sends data to a connected Socket, starting at the indicated location in the data. Send Overloaded: Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) Sends data to a connected Socket, starting at the indicated location in the data. SendTo Overloaded: SendTo(byte[] buffer, EndPoint remoteEP) Sends data to a specific endpoint. SendTo Overloaded: SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP) Sends data to a specific endpoint. SendTo Overloaded: SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP) Sends data to a specific endpoint. SendTo Overloaded: SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) Sends data to a specific endpoint, starting at the indicated location in the data. SetSocketOption Overloaded: SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) Sets the specified option to the specified value. SetSocketOption Overloaded: SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) Sets the specified option to the specified value. SetSocketOption Overloaded: SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue) Sets the specified option to the specified value. Shutdown Disables sends and receives on a Socket. ToString (inherited from System.Object) See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. Protected Methods Dispose Disposes of the unmanaged resources (other than memory) used by the Socket, and optionally disposes of the managed resources. Finalize Overridden: Frees resources used by the Socket class. MemberwiseClone (inherited from System.Object) See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. Hierarchy: System.Object System.Net.Sockets.Socket System.Net.Sockets.Socket Member Detailsctor #1 Summary Initializes a new instance of the Socket class. C# Syntax: public Socket(AddressFamily addressFamily, Socket( AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType ); Parameters: addressFamily One of the AddressFamily values. socketType One of the SocketType values. protocolType One of the ProtocolType values. Exceptions Exception Type Condition SocketException The combination of addressFamily, socketType, and protocolType results in an invalid socket. Remarks The addressFamily parameter specifies the addressing scheme that the Socket uses, the socketType parameter specifies the type of the Socket, and the protocolType parameter specifies the protocol used by the Socket. The three parameters are not independent. Some address families restrict which protocols can be used with them, and often the socket type is implicit in the protocol. If the combination of address family, socket type, and protocol type results in an invalid Socket, a SocketException is thrown. The AddressFamily enumeration defines the valid address families, the SocketType enumeration defines the valid socket types, and the ProtocolType enumeration defines the valid protocol types. Example The following example demonstrates how to create an instance of Socket.
IPAddress hostadd = Dns.Resolve(server).AddressList[0];
IPEndPoint EPhost = new IPEndPoint(hostadd, 80);
//Creates the Socket for sending data over TCP.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp );
Return to top Property: AddressFamily (read-only) Summary Gets the address family of the Socket. C# Syntax: public AddressFamily AddressFamily {get;} Remarks AddressFamily specifies the addressing scheme that an instance of the Socket class can use. This property is read-only and is set when the Socket is created. Example The following example displays the AddressFamily, SocketType, and ProtocolType to the console.
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
//Using the AddressFamily, SocketType, and ProtocolType properties.
Console.WriteLine("I just set the following properties of socket: " +
"Address Family = " + s.AddressFamily.ToString() +
"\nSocketType = " + s.SocketType.ToString() +
"\nProtocolType = " + s.ProtocolType.ToString());
See also: AddressFamily Return to top Property: Available (read-only) Summary Gets the amount of data that has been received from the network and is available to be read. C# Syntax: public int Available {get;} Exceptions Exception Type Condition SocketException An error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you are using a Stream Socket type, the available data is generally the total amount of data queued on the current instance. If you are using a message-oriented Socket type such as SocketType.Dgram, the available data is the first message in the input queue. Example The following example uses Socket.Available to determine how many bytes to read into a local buffer.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, msg.Length, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, s.Available, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
Return to top Property: Blocking (read-write) Summary Gets or sets a value that indicates whether the Socket is in blocking mode. C# Syntax: public bool Blocking {get; set;} Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.Blocking property indicates whether a Socket is in blocking mode. Sockets are created in blocking mode by default. To set the Socket to not block, set Socket.Blocking to false. Return to top Property: Connected (read-only) Summary Gets a value indicating whether a Socket is connected to a remote resource. C# Syntax: public bool Connected {get;} Remarks Gets the connection state of the Socket. This property will return the latest known state of the Socket. When it returns false, the Socket was either never connected, or no longer connected. When it returns true, the Socket was connected at the time of the last I/O operation. Note There is no guarantee that the Socket is still Socket.Connected even though Socket.Connected returns true. Example The following example connects to a remote endpoint and then verifies the connection.
aSocket.Connect(anEndPoint);
if (!aSocket.Connected) {
Console.WriteLine("Winsock error: "
+ Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
}
Return to top Property: Handle (read-only) Summary Gets the operating system handle for the Socket. C# Syntax: public IntPtr Handle {get;} Return to top Property: LocalEndPoint (read-only) Summary Gets the local endpoint. C# Syntax: public EndPoint LocalEndPoint {get;} Exceptions Exception Type Condition SocketException An error occurs while reading the property. ObjectDisposedException The Socket has been closed. Remarks The Socket.LocalEndPoint property contains the network connection information associated with the local network device. Socket.LocalEndPoint is set by calling the Socket.Bind method. Example The following example retrieves and displays the local and remote endpoints.
s.Connect(lep);
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) +
"on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.ToString()) +
"I am connected on port number " +
((IPEndPoint)s.LocalEndPoint).Port.ToString());
Return to top Property: ProtocolType (read-only) Summary Gets the protocol type of the Socket. C# Syntax: public ProtocolType ProtocolType {get;} Remarks Socket.ProtocolType is set when the Socket is created, and specifies the protocol used by that Socket. Example The following example displays the AddressFamily, SocketType, and ProtocolType to the console.
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
//Using the AddressFamily, SocketType, and ProtocolType properties.
Console.WriteLine("I just set the following properties of socket: " +
"Address Family = " + s.AddressFamily.ToString() +
"\nSocketType = " + s.SocketType.ToString() +
"\nProtocolType = " + s.ProtocolType.ToString());
Return to top Property: RemoteEndPoint (read-only) Summary Gets the remote endpoint. C# Syntax: public EndPoint RemoteEndPoint {get;} Exceptions Exception Type Condition SocketException An error occurs while reading the property. ObjectDisposedException The Socket has been closed. Remarks The Socket.RemoteEndPoint property gets the network connection information associated with the remote host. Socket.RemoteEndPoint is set by Socket methods that establish a connection to a remote host. Example The following example retrieves and displays the local and remote endpoints.
s.Connect(lep);
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) +
"on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.ToString()) +
"I am connected on port number " +
((IPEndPoint)s.LocalEndPoint).Port.ToString());
See also: Socket.BeginConnect | Socket.BeginReceiveFrom | Socket.BeginSendTo | Socket.Connect | Socket.ReceiveFrom | Socket.SendTo Return to top Property: SocketType (read-only) Summary Gets the type of the Socket. C# Syntax: public SocketType SocketType {get;} Remarks Socket.SocketType is set when the class is created. Example The following example displays the AddressFamily, SocketType, and ProtocolType to the console.
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
//Using the AddressFamily, SocketType, and ProtocolType properties.
Console.WriteLine("I just set the following properties of socket: " +
"Address Family = " + s.AddressFamily.ToString() +
"\nSocketType = " + s.SocketType.ToString() +
"\nProtocolType = " + s.ProtocolType.ToString());
See also: SocketType Return to top Method: Accept() Summary Creates a new Socket to handle an incoming connection request. C# Syntax: public Socket Accept(); Return Value: A Socket to handle an incoming connection request. Exceptions Exception Type Condition SocketException The Socket is invalid. ObjectDisposedException The Socket has been closed. Remarks The Socket.Accept method extracts the first connection request from the queue of pending requests and creates a new Socket to handle it. Example The following example accepts a simple Socket connection.
Socket mySocket = listeningSocket.Accept();
if (mySocket == null)
{
Console.WriteLine("Winsock error: " +
Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );
}
Return to top Method: BeginAccept( AsyncCallback callback, object state ) Summary Begins an asynchronous request to create a new Socket to accept an incoming connection request. C# Syntax: public IAsyncResult BeginAccept( AsyncCallback callback, object state ); Parameters: callback The AsyncCallback delegate. state An object containing state information for this request. Return Value: An IAsyncResult that references the asynchronous Socket creation. Exceptions Exception Type Condition SocketException An operating system error occurs while creating the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.BeginAccept method starts an asynchronous request to create a Socket to handle an incoming connection request. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndAccept method to retrieve the Socket. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example attempts to receive an incoming connection asynchronously.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Bind(lep);
s.Listen(1000);
while(true){
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
s.BeginAccept(new AsyncCallback(Async_Send_Receive.Listen_Callback), s);
allDone.WaitOne();
}
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
See also: MSDN: asynchronousprogramming Return to top Method: BeginConnect( EndPoint remoteEP, AsyncCallback callback, object state ) Summary Begins an asynchronous request for a connection to a network device. C# Syntax: public IAsyncResult BeginConnect( EndPoint remoteEP, AsyncCallback callback, object state ); Parameters: remoteEP An EndPoint that represents the remote device. An EndPoint that represents the remote device. callback The AsyncCallback delegate. state An object that contains state information for this request. Return Value: An IAsyncResult that references the asynchronous connection. Exceptions Exception Type Condition ArgumentNullException The remoteEP parameter is null. SocketException An operating system error occurs while creating the Socket. ObjectDisposedException The Socket[ cref, System.Net.Sockets] has been closed. Remarks The Socket.BeginConnect method starts an asynchronous request for a remote host connection. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndConnect method to return the Socket. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example initiates an asynchronous connection attempt.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
while(true){
allDone.Reset();
Console.WriteLine("Establishing Connection");
s.BeginConnect(lep, new AsyncCallback(Async_Send_Receive.Connect_Callback), s);
allDone.WaitOne();
}
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
See also: MSDN: asynchronousprogramming Return to top Method: BeginReceive( byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state ) Summary Begins to asynchronously receive data from a connected Socket. C# Syntax: public IAsyncResult BeginReceive( byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state ); Parameters: buffer The storage location for the received data. offset The zero-based position in the buffer parameter at which to store the received data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. callback The AsyncCallback delegate. state An object containing state information for this request. Return Value: An IAsyncResult that references the asynchronous read. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException Socket has been closed. ArgumentOutOfRangeException The offset parameter is outside the bounds of buffer or size is either smaller or larger than the buffer size. SocketException An operating system error occurred while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.BeginReceive method starts asynchronously reading data from a Socket. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndReceive method to return the data read from the Socket. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example begins to asynchronously receive data from a connected Socket.
allDone.Set();
Socket s = (Socket) ar.AsyncState;
Socket s2 = s.EndAccept(ar);
StateObject so2 = new StateObject();
so2.workSocket = s2;
s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so2);
See also: MSDN: asynchronousprogramming Return to top Method: BeginReceiveFrom( byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state ) Summary Begins to asynchronously receive data from a specified network device. C# Syntax: public IAsyncResult BeginReceiveFrom( byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state ); Parameters: buffer The storage location for the received data. offset The zero-based position in the buffer parameter at which to store the data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. remoteEP An EndPoint that represents the source of the data. callback The AsyncCallback delegate. state An object containing state information for this request. Return Value: An IAsyncResult that references the asynchronous read. Exceptions Exception Type Condition ArgumentException The buffer parameter is null. -or- The remoteEP parameter is null. -or- The offset parameter is outside the bounds of buffer. SocketException An operating system error occurs while accessing the Socket. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. ObjectDisposedException The Socket has been closed. Remarks The Socket.BeginReceiveFrom method starts asynchronously reading data from a socket. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndReceiveFrom method to return the data read from the Socket. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example asynchronously receives connectionless datagrams from a remote host.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
try{
while(true){
allDone.Reset();
StateObject so2 = new StateObject();
so2.workSocket = s;
Console.WriteLine("Attempting to Receive data from host.contoso.com");
s.BeginReceiveFrom(so2.buffer, 0, StateObject.BUFFER_SIZE,0, ref tempRemoteEP,
new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so2);
allDone.WaitOne();
}
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
See also: MSDN: asynchronousprogramming Return to top Method: BeginSend( byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state ) Summary Sends data asynchronously to a connected Socket. C# Syntax: public IAsyncResult BeginSend( byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state ); Parameters: buffer The data to send. offset The zero-based position in the buffer parameter at which to begin sending data. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. callback The AsyncCallback delegate. state An object containing state information for this request. Return Value: An IAsyncResult that references the asynchronous send. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. SocketException An operating system error occurs while accessing the Socket. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. ObjectDisposedException The Socket has been closed. Remarks The Socket.BeginSend method starts asynchronously sending data through a socket. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndSend method to complete sending data. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example begins asynchronously sending data to a remote host.
allDone.Set();
Socket s = (Socket) ar.AsyncState;
s.EndConnect(ar);
StateObject so2 = new StateObject();
so2.workSocket = s;
byte[] buff = Encoding.ASCII.GetBytes("This is a test");
s.BeginSend(buff, 0, buff.Length,0,
new AsyncCallback(Async_Send_Receive.Send_Callback), so2);
See also: MSDN: asynchronousprogramming Return to top Method: BeginSendTo( byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state ) Summary Sends data asynchronously to a specific remote host. C# Syntax: public IAsyncResult BeginSendTo( byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state ); Parameters: buffer The data to send. offset The zero-based position in the buffer parameter at which to begin sending data. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. remoteEP An EndPoint that represents the remote device. callback The AsyncCallback delegate. state An object containing state information for this request. Return Value: An IAsyncResult that references the asynchronous send. Exceptions Exception Type Condition ArgumentException The buffer parameter is null. -or- The remoteEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. ObjectDisposedException The Socket has been closed. Remarks The Socket.BeginSendTo method starts asynchronously sending data through a socket. You must create a callback method that implements the AsyncCallback delegate. This callback method should use the Socket.EndSendTo method to complete sending data. Note For additional information on writing callback methods see the conceptual topic at MSDN: callbacksample. Example The following example asynchronously sends data to the specified remote host.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
while(true){
allDone.Reset();
byte[] buff = Encoding.ASCII.GetBytes("This is a test");
Console.WriteLine("Sending Message Now..");
s.BeginSendTo(buff, 0, buff.Length, 0, lep, new AsyncCallback(Async_Send_Receive.SendTo_Callback), s);
allDone.WaitOne();
}
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
See also: MSDN: asynchronousprogramming Return to top Method: Bind( EndPoint localEP ) Summary Associates a Socket with a local endpoint. C# Syntax: public void Bind( EndPoint localEP ); Parameters: localEP The local EndPoint to associate with the Socket. Exceptions Exception Type Condition ArgumentNullException The localEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you want to use a specific local endpoint, you can call the Socket.Bind method before you call the Socket.Listen or Socket.Connect methods. Example The following example binds a Socket using the specified local endpoint.
try {
aSocket.Bind(anEndPoint);
}
catch (Exception e) {
Console.WriteLine("Winsock error: " + e.ToString());
}
.NET Framework Security: SocketPermission for accepting connections from the host defined by localEP. Associated enumeration: NetworkAccess.Accept Return to top Method: Close() Summary Forces a Socket connection to close. C# Syntax: public void Close(); Remarks The Socket.Connected property is set to false when the socket is closed. The application should call Socket.Shutdown before calling Socket.Close to ensure that all pending data is sent or received before the Socket is closed. Example The following example closes a Socket.
aSocket.Shutdown(SocketShutdown.Both);
aSocket.Close();
if (aSocket.Connected) {
Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );
}
Return to top Method: Connect( EndPoint remoteEP ) Summary Establishes a connection to a remote device. C# Syntax: public void Connect( EndPoint remoteEP ); Parameters: remoteEP An EndPoint that represents the remote device. Exceptions Exception Type Condition ArgumentNullException The remoteEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.Connect method establishes a network connection between Socket.LocalEndPoint and the device identified by the remoteEP parameter. Once the connection has been made, you can send data to the remote device with the Socket.Send method, or receive data from the remote device with the Socket.Receive method. Example The following example connects to a remote endpoint and then verifies the connection.
aSocket.Connect(anEndPoint);
if (!aSocket.Connected) {
Console.WriteLine("Winsock error: "
+ Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
}
.NET Framework Security: SocketPermission for connecting to the remote host. Associated enumeration: NetworkAccess.Connect Return to top Method: Dispose( bool disposing ) Summary Disposes of the unmanaged resources (other than memory) used by the Socket, and optionally disposes of the managed resources. C# Syntax: protected virtual void Dispose( bool disposing ); Parameters: disposing If true, releases both managed and unmanaged resources; if false, releases only unmanaged resources. Remarks This method is called by the public Dispose() method and the Object.Finalize method.Dispose() invokes the protected Dispose(Boolean) method with the disposing parameter set to true. Object.Finalize invokes Dispose with disposing set to false. When the disposing parameter is true, this method releases all resources held by any managed objects that this Socket references. This method invokes the Dispose() method of each referenced object. Notes to inheritors: Dispose can be called multiple times by other objects. When overriding Dispose(Boolean), be careful not to reference objects that have been previously disposed of in an earlier call to Dispose. For more information about how to implement Dispose(Boolean), see the conceptual topic at MSDN: implementingdisposemethod. Return to top Method: EndAccept( IAsyncResult asyncResult ) Summary Ends an asynchronous request to create a new Socket to accept an incoming connection request. C# Syntax: public Socket EndAccept( IAsyncResult asyncResult ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user defined data. Return Value: A Socket to handle the incoming connection. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not created by a call to Socket.BeginAccept. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.EndAccept method completes a request for a connection that was started with the Socket.BeginAccept method. Example The following example ends an asynchronous request and creates a new Socket to accept an incoming connection request.
allDone.Set();
Socket s = (Socket) ar.AsyncState;
Socket s2 = s.EndAccept(ar);
StateObject so2 = new StateObject();
so2.workSocket = s2;
s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so2);
See also: MSDN: asynchronousprogramming Return to top Method: EndConnect( IAsyncResult asyncResult ) Summary Ends a pending asynchronous connection request. C# Syntax: public void EndConnect( IAsyncResult asyncResult ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user-defined data. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not returned by a call to the Socket.BeginConnect method. InvalidOperationException Socket.EndConnect was previously called for the asynchronous connection. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks To maintain the asynchronous nature of the operation, call this method from the callback delegate. You can pass either the IAsyncResult returned from Socket.BeginConnect or the callback delegate used as an input parameter to Socket.BeginConnect as the asyncresult parameter. The Socket.EndConnect method blocks. Example The following example ends the asynchronous connection attempt.
allDone.Set();
Socket s = (Socket) ar.AsyncState;
s.EndConnect(ar);
StateObject so2 = new StateObject();
so2.workSocket = s;
byte[] buff = Encoding.ASCII.GetBytes("This is a test");
s.BeginSend(buff, 0, buff.Length,0,
new AsyncCallback(Async_Send_Receive.Send_Callback), so2);
See also: MSDN: asynchronousprogramming Return to top Method: EndReceive( IAsyncResult asyncResult ) Summary Ends a pending asynchronous read. C# Syntax: public int EndReceive( IAsyncResult asyncResult ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user defined data. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not returned by a call to the Socket.BeginReceive method. InvalidOperationException Socket.EndReceive was previously called for the asynchronous read. SocketException An operating system error occurs while accessing the socket. ObjectDisposedException The Socket has been closed. Remarks To maintain the asynchronous nature of the operation, call this method from the callback delegate. You can pass either the IAsyncResult returned from Socket.BeginReceive or the callback delegate used as an input parameter to Socket.BeginReceive as the asyncResult parameter. The Socket.EndReceive method blocks until the read ends. The Socket.EndReceive method frees any resources allocated by the Socket.BeginReceive method. Example The following example ends a pending asynchronous read.
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
int read = s.EndReceive(ar);
if (read > 0) {
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so);
}
else{
if (so.sb.Length > 1) {
//All of the data has been read, so displays it to the console
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));
}
s.Close();
}
See also: MSDN: asynchronousprogramming Return to top Method: EndReceiveFrom( IAsyncResult asyncResult, ref EndPoint endPoint ) Summary Ends a pending asynchronous read from a specific endpoint. C# Syntax: public int EndReceiveFrom( IAsyncResult asyncResult, ref EndPoint endPoint ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user defined data. endPoint The source EndPoint. Return Value: If successful, the number of bytes received. If unsuccessful, returns 0 if the connection is closed by the remote host. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not returned by a call to the Socket.BeginReceiveFrom method. InvalidOperationException Socket.EndReceiveFrom was previously called for the asynchronous read. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks To maintain the asynchronous nature of the operation, call this method from the callback delegate. You can pass either the IAsyncResult returned from Socket.BeginReceiveFrom or the callback delegate used as an input parameter to Socket.BeginReceiveFrom. as the asyncResult parameter. The EndReceiveFrom method frees any resources allocated by the BeginReceiveFrom method. The Socket.EndReceiveFrom method blocks until read ends. Example The following example ends a pending asynchronous read from a specific EndPoint.
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
// Creates a temporary EndPoint to pass to EndReceiveFrom.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
int read = s.EndReceiveFrom(ar, ref tempRemoteEP);
if (read > 0) {
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE, 0, ref tempRemoteEP,
new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so);
}
else{
if (so.sb.Length > 1) {
//All the data has been read, so displays it to the console.
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));
}
s.Close();
}
See also: MSDN: asynchronousprogramming Return to top Method: EndSend( IAsyncResult asyncResult ) Summary Ends a pending asynchronous send. C# Syntax: public int EndSend( IAsyncResult asyncResult ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user defined data. Return Value: If successful, the number of bytes sent to the Socket; otherwise, an invalid Socket error. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not returned by a call to the Socket.BeginSend method. InvalidOperationException Socket.EndSend was previously called for the asynchronous read. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks To maintain the asynchronous nature of the operation, call this method from the callback delegate. You can pass either the IAsyncResult returned from Socket.BeginSend or the callback delegate used as an input parameter to Socket.BeginSend as the asyncResult parameter. The EndSend method frees any resources allocated by the BeginSend method. The Socket.EndSend method blocks until the send ends. The Socket.EndSend method frees any resources allocated by the Socket.BeginSend method. Example The following example ends a pending asynchronous send.
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
int send = s.EndSend(ar);
Console.WriteLine("The size of the message sent was :" + send.ToString());
s.Close();
See also: MSDN: asynchronousprogramming Return to top Method: EndSendTo( IAsyncResult asyncResult ) Summary Ends a pending asynchronous send to a specific location. C# Syntax: public int EndSendTo( IAsyncResult asyncResult ); Parameters: asyncResult Stores state information for this asynchronous operation as well as any user defined data . Return Value: If successful, the number of bytes sent; otherwise, an invalid Socket error. Exceptions Exception Type Condition ArgumentNullException The asyncResult parameter is null. ArgumentException The asyncResult parameter was not returned by a call to the Socket.BeginSendTo method. InvalidOperationException Socket.EndSendTo was previously called for the asynchronous read. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks To maintain the asynchronous nature of the operation, call this method from the callback delegate. You can pass either the IAsyncResult returned from Socket.BeginSendTo or the callback delegate used as an input parameter to Socket.BeginSendTo as the asyncResult parameter. The EndSendTo method frees any resources allocated by the BeginSendTo method. The Socket.EndSendTo method blocks until send is complete. The Socket.EndSendTo method frees any resources allocated by the Socket.BeginSendTo method. Example The following example ends an asynchronous send to a specific location.
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;
int send = s.EndSendTo(ar);
Console.WriteLine("The size of the message sent was :" + send.ToString());
s.Close();
See also: MSDN: asynchronousprogramming Return to top Method: Equals( object obj ) Inherited See base class member description: System.Object.Equals C# Syntax: public virtual bool Equals( object obj ); For more information on members inherited from System.Object click on the link above. Return to top Overridden Method: Finalize() Summary Frees resources used by the Socket class. C# Syntax: ~Socket(); Remarks The Socket class finalizer calls the Socket.Close method to close the Socket and free resources associated with the Socket. Return to top Overridden Method: GetHashCode() C# Syntax: public override int GetHashCode(); Return to top Overloaded Method: GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName ) Summary Gets the value of a specified socket option. C# Syntax: public object GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName ); Parameters: optionLevel One of the SocketOptionLevel values. optionName One of the SocketOptionName values. Return Value: The value of the option. When the optionName parameter is set to SocketOptionName.Linger the return value is an instance of the LingerOption. When optionName is set to SocketOptionName.AddMembership or SocketOptionName.DropMembership, the return value is an instance of the MulticastOption. When optionName is any other value, the return value is an integer. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Socket options determine the behavior of the current instance. Upon successful completion, Socket.GetSocketOption returns an object describing the requested option. For example, if you specify SocketOptionName.Linger as the option, a LingerOption is returned. Example The following example retrieves the LingerOption and Socket.Send time-out values and displays them to the console.
Console.WriteLine("This application will timeout if Send does not return within " +
Encoding.ASCII.GetString(s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.SendTimeout, 4)));
// blocks until send returns
int i = s.Send(msg);
// blocks until read returns
byte[] bytes = new byte[1024];
s.Receive(bytes);
//Display to the screen
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
Console.WriteLine("If data remains to be sent, this application will stay open for " +
((LingerOption) s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.Linger)).LingerTime.ToString());
s.Close();
Return to top Overloaded Method: GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue ) Summary Gets the specified Socket option setting. C# Syntax: public void GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue ); Parameters: optionLevel One of the SocketOptionLevel values. optionName One of the SocketOptionName values. optionValue The buffer that is to receive the option setting. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Socket options determine the behavior of the current Socket. Upon successful completion of this method, 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 is thrown. Example The following example retrieves the LingerOption and Socket.Send time-out values and displays them to the console.
Console.WriteLine("This application will timeout if Send does not return within " +
Encoding.ASCII.GetString(s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.SendTimeout, 4)));
// blocks until send returns
int i = s.Send(msg);
// blocks until read returns
byte[] bytes = new byte[1024];
s.Receive(bytes);
//Display to the screen
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
Console.WriteLine("If data remains to be sent, this application will stay open for " +
((LingerOption) s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.Linger)).LingerTime.ToString());
s.Close();
Return to top Overloaded Method: GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength ) Summary Returns the value of the specified Socket option and returns in an array. C# Syntax: public byte[] GetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength ); Parameters: optionLevel One of the SocketOptionLevel values. optionName One of the SocketOptionName values. optionLength The length, in bytes, of the expected return value. Return Value: An array of bytes containing the value of the socket option. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The optionLength parameter sets the maximum size of the returned byte array. If the option value requires fewer bytes, the array will contain only that many bytes. If the option value requires more bytes, a SocketException will be thrown. Example The following example retrieves the LingerOption and Socket.Send time-out values and displays them to the console.
Console.WriteLine("This application will timeout if Send does not return within " +
Encoding.ASCII.GetString(s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.SendTimeout, 4)));
// blocks until send returns
int i = s.Send(msg);
// blocks until read returns
byte[] bytes = new byte[1024];
s.Receive(bytes);
//Display to the screen
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
Console.WriteLine("If data remains to be sent, this application will stay open for " +
((LingerOption) s.GetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.Linger)).LingerTime.ToString());
s.Close();
Return to top Method: GetType() Inherited See base class member description: System.Object.GetType C# Syntax: public Type GetType(); For more information on members inherited from System.Object click on the link above. Return to top Method: IOControl( int ioControlCode, byte[] optionInValue, byte[] optionOutValue ) Summary Sets low-level operating modes for the Socket. C# Syntax: public int IOControl( int ioControlCode, byte[] optionInValue, byte[] optionOutValue ); Parameters: ioControlCode The control code of the operation to perform. optionInValue The input data required by the operation. optionOutValue The output data returned by the operation. Return Value: The number of bytes in optionOutValue parameter. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks The Socket.IOControl method provides low-level access to the operating system socket underlying the current instance of the Socket class. For more information about Socket.IOControl, see the WSAIoct documentation in MSDN. Example The following example uses Socket.IOControl to set the socket to blocking mode.
s.Connect(lep);
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) +
"on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.ToString()) +
"I am connected on port number " +
((IPEndPoint)s.LocalEndPoint).Port.ToString());
Return to top Method: Listen( int backlog ) Summary Places a Socket in a listening state. C# Syntax: public void Listen( int backlog ); Parameters: backlog The Maximum length of the queue of pending connections. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks In a listening state, the Socket will poll for incoming connection attempts. If you want to listen using a specific network interface on a specific port, you must call the Socket.Bind method first. Example The following example uses Socket to listen for incoming connections.
// Allows a queue of 10 connections.
aSocket.Listen(10);
if (!aSocket.Connected) {
Console.WriteLine("Winsock error: "
+ Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
}
Return to top Method: MemberwiseClone() Inherited See base class member description: System.Object.MemberwiseClone C# Syntax: protected object MemberwiseClone(); For more information on members inherited from System.Object click on the link above. Return to top Method: Poll( int microSeconds, SelectMode mode ) Summary Determines the status of the Socket. C# Syntax: public bool Poll( int microSeconds, SelectMode mode ); Parameters: microSeconds The time to wait for a response, in microseconds. mode One of the SelectMode values. Return Value: Mode Return Value SelectMode.SelectRead true if Socket.Listen has been called and a connection is pending, Socket.Accept will succeed -or- true if data is available for reading -or- true, if connection has been closed, reset, or terminated; otherwise, returns false. SelectMode.SelectWrite true, if processing a Socket.Connect, and the connection has succeeded -or- true, if data can be sent; otherwise, returns false. SelectMode.SelectError true, if processing a Socket.Connect that does not block, and the connection has failed -or- true, if SocketOptionName.OutOfBandInline is not set and out-of-band data is available; otherwise, returns false. Exceptions Exception Type Condition NotSupportedException The mode parameter is not one of the SelectMode values. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Set microSeconds parameter to a negative integer if you would like to wait indefinitely for a response. Return to top Overloaded Method: Receive( byte[] buffer ) Summary Receives data from a connected Socket into a specific location of the receive buffer. C# Syntax: public int Receive( byte[] buffer ); Parameters: buffer The storage location for the received data. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer. The offset defaults to 0, size defaults to the buffer length, and the socketFlags value defaults to SocketFlags.None. The Socket.Blocking determines the behavior of this method when no incoming data is available. When false, a SocketException is thrown. When true, this method blocks and waits for data to arrive. For stream Socket types, if the remote Socket was shut down gracefully, and all the data was received, this method immediately returns zero, regardless of the blocking state. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter , buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. Example The following example receives data on a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: Receive( byte[] buffer, SocketFlags socketFlags ) Summary Receives data from a connected Socket into a specific location of the receive buffer. C# Syntax: public int Receive( byte[] buffer, SocketFlags socketFlags ); Parameters: buffer The storage location for the received data. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer and the necessary SocketFlags. The offset defaults to 0, and the size defaults to the buffer length. You must set the Socket.LocalEndPoint property before calling this method. The Socket.Blocking determines the behavior of this method when no incoming data is available. When false, a SocketException is thrown. When true, this method blocks and waits for data to arrive. For Stream Socket types, if the remote Socket was shut down gracefully, and all the data was received, this method immediately returns zero, regardless of the blocking state. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. Note If you specify the SocketFlags.OutOfBand flag as the socketFlags parameter, and the Socket is configured for in-line reception of out-of-band (OOB) data (using the SocketOptionName.OutOfBandInline option) and OOB data is available, then only OOB data is returned. When the SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but is not removed from the system buffer. Example The following example specifies a data buffer, and SocketFlags for receiving data on a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: Receive( byte[] buffer, int size, SocketFlags socketFlags ) Summary Receives data from a connected Socket into a specific location of the receive buffer. C# Syntax: public int Receive( byte[] buffer, int size, SocketFlags socketFlags ); Parameters: buffer The storage location for the received data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. ArgumentOutOfRangeException The size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer, the number of bytes you want to send, and the necessary SocketFlags. The offset defaults to 0. You must set the Socket.LocalEndPoint property before calling this method. The Socket.Blocking determines the behavior of this method when no incoming data is available. When false, a SocketException is thrown. When true, this method blocks and waits for data to arrive. For Stream Socket types, if the remote Socket was shut down gracefully, and all the data was received, this method immediately returns zero, regardless of the blocking state. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. Note If you specify the SocketFlags.OutOfBand flag as the socketFlags parameter, and the Socket is configured for in-line reception of out-of-band (OOB) data (using the SocketOptionName.OutOfBandInline option) and OOB data is available, then only OOB data is returned. When the SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but is not removed from the system buffer. Example The following receives the data found into buffer, and specifies SocketFlags.None for SocketFlags.
// Receives the page, loops until all bytes are received.
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = "Default HTML page on " + server + ":\r\n";
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: Receive( byte[] buffer, int offset, int size, SocketFlags socketFlags ) Summary Receives data from a connected Socket in a specific location of the receive buffer. C# Syntax: public int Receive( byte[] buffer, int offset, int size, SocketFlags socketFlags ); Parameters: buffer The storage location for received data. offset The location in buffer to store the received data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException buffer is null. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks You must set the Socket.LocalEndPoint property before calling this method. The Socket.Blocking determines the behavior of this method when no incoming data is available. When false, a SocketException is thrown. When true, this method blocks and waits for data to arrive. For Stream Socket types, if the remote Socket was shut down gracefully, and all the data was received, this method immediately returns zero, regardless of the blocking state. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. Note If you specify the SocketFlags.OutOfBand flag as the socketFlags parameter, and the Socket is configured for in-line reception of out-of-band (OOB) data (using the SocketOptionName.OutOfBandInline option) and OOB data is available, then only OOB data is returned. When the SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but is not removed from the system buffer. Example The following example specifies a data buffer, an offset, a size, and a Socket Flag before receiving data on a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, 0, msg.Length, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, 0, s.Available, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: ReceiveFrom( byte[] buffer, ref EndPoint remoteEP ) Summary Receives a datagram in a specific location in the data buffer and stores the endpoint. C# Syntax: public int ReceiveFrom( byte[] buffer, ref EndPoint remoteEP ); Parameters: buffer The storage location for received data. remoteEP An EndPoint, passed by reference, that represents the remote server. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. -or- The remoteEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer, and EndPoint representing the remote host. The offset defaults to 0. The size defaults to the buffer length . and the socketFlags value defaults to SocketFlags.None. If you use a connectionless protocol, the remoteEP parameter contains the EndPoint associated with the Socket that sent the data. If you use a connection-oriented protocol, remoteEP is left unchanged. You must set the Socket.LocalEndPoint property before calling this method. When no incoming data is available, and the Socket.Blocking property is false, a SocketException is thrown. When Socket.Blocking is true, this method blocks and waits for data to arrive. For 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. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, then buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. Example The following example receives a connectionless datagram from a remote host.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: ReceiveFrom( byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP ) Summary Receives a datagram in a specific location in the data buffer and stores the endpoint. C# Syntax: public int ReceiveFrom( byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP ); Parameters: buffer The storage location for the received data. socketFlags A bitwise combination of the SocketFlags values. remoteEP An EndPoint, passed by reference, that represents the remote server. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null -or- The remoteEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer, the necessary SocketFlags, and the EndPoint representing the remote host. The offset defaults to 0. The size defaults to the buffer length. If you use a connectionless protocol, the remoteEP parameter contains the EndPoint associated with the Socket that sent the data. If you use a connection-oriented protocol, remoteEP is left unchanged. You must set the Socket.LocalEndPoint property before calling this method. When no incoming data is available, and the Socket.Blocking property is false, a SocketException is thrown. When Socket.Blocking is true, this method blocks and waits for data to arrive. For 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. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, then buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. When the SocketFlags.OutOfBand flag is specified as the socketFlags parameter and the Socket is configured for in-line reception of out-of-band (OOB) data (using SocketOptionName.OutOfBandInline) and OOB data is available, only OOB data is returned. When the SocketFlags. SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but not removed from the system buffer. Example The following example receives a connectionless datagram from a remote host. SocketFlags are passed to the Socket.ReceiveFrom method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive themessage.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: ReceiveFrom( byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP ) Summary Receives a datagram in a specific location in the data buffer and stores the endpoint. C# Syntax: public int ReceiveFrom( byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP ); Parameters: buffer The storage location for received data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. remoteEP An EndPoint, passed by reference, that represents the remote server. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null - or- The remoteEP parameter is null. ArgumentOutOfRangeException The size parameter exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks This overload only requires you to provide a receive buffer, the number of bytes you want to receive, the necessary SocketFlags, and the EndPoint representing the remote host. The offset defaults to 0. If you use a connectionless protocol, the remoteEP parameter contains the EndPoint associated with the Socket that sent the data. If you use a connection-oriented protocol, remoteEP is left unchanged. You must set the Socket.LocalEndPoint property before calling this method. When no incoming data is available, and the Socket.Blocking property is false, a SocketException is thrown. When Socket.Blocking is true, this method blocks and waits for data to arrive. For 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. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, then buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. When the SocketFlags.OutOfBand flag is specified asthe socketFlags parameter and the Socket is configured for in-line reception of out-of-band (OOB) data (using SocketOptionName.OutOfBandInline) and OOB data is available, only OOB data is returned. When the SocketFlags. SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but not removed from the system buffer. Example The following example receives a connectionless datagram from a remote host. The buffer size, and SocketFlags are passed to the Socket.ReceiveFrom method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, msg.Length, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, 100, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Overloaded Method: ReceiveFrom( byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP ) Summary Receives a datagram in a specific location in the data buffer and stores the endpoint. C# Syntax: public int ReceiveFrom( byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP ); Parameters: buffer The storage location for received data. offset The position in the buffer parameter to store the received data. size The number of bytes to receive. socketFlags A bitwise combination of the SocketFlags values. remoteEP An EndPoint, passed by reference, that represents the remote server. Return Value: The number of bytes received. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. - or- The remoteEP parameter is null. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you use a connectionless protocol, the remoteEP parameter contains the EndPoint associated with the Socket that sent the data. If you use a connection-oriented protocol, remoteEP is left unchanged. You must set the Socket.LocalEndPoint property before calling this method. When no incoming data is available, and the Socket.Blocking property is false, a SocketException is thrown. When Socket.Blocking is true, this method blocks and waits for data to arrive. For 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. If you are using a message-oriented Socket, and the message is larger than the size of the buffer parameter, then buffer is filled with the first part of the message, and a SocketException is thrown. With unreliable protocols the excess data is lost; with reliable protocols, the data is retained by the service provider. When the SocketFlags.OutOfBand flag is specified as the socketFlags parameter and the Socket is configured for in-line reception of out-of-band (OOB) data (using SocketOptionName.OutOfBandInline) and OOB data is available, only OOB data is returned. When the SocketFlags. SocketFlags.Peek flag is specified as the socketFlags parameter, available data is copied into the receive buffer but not removed from the system buffer. Example The following example receives a connectionless datagram from a remote host. The offset, buffer size, and SocketFlags are passed to the Socket.ReceiveFrom method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, 0, msg.Length, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, 0, 100, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen.
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
.NET Framework Security: SocketPermission for accepting connections from the network. Associated enumeration: NetworkAccess.Accept. Return to top Method: Select( IList checkRead, IList checkWrite, IList checkError, int microSeconds ) Summary Determines the status of one or more sockets. C# Syntax: public static void Select( IList checkRead, IList checkWrite, IList checkError, int microSeconds ); Parameters: checkRead An IList of Socket instances to check for data to read. checkWrite An IList of Socket instances to check for writing availability. checkError An IList of Socket instances to check for errors. microSeconds The time to wait for a response, in microseconds. Exceptions Exception Type Condition ArgumentNullException The checkRead parameter is null or empty. -and- The checkWrite parameter is null or empty -and- The checkError parameter is null or empty. SocketException An operating system error occurs while accessing the Socket. Remarks Socket.Select is a static method that determines the status of a set of Socket instances. For example, to determine which of a set of Socket instances has data ready to be read, place the sockets in an IList, and then call Socket.Select using the IList as the checkRead parameter. After the call to Socket.Select, the IList will contain only those sockets with data ready to be read. Example The following example uses Socket.Select to determine which sockets have data to be read.
IPHostEntry lipa = Dns.Resolve(Dns.GetHostName());
//Gets three separate local endpoints.
IPEndPoint lep1 = new IPEndPoint(lipa.AddressList[0], 11000);
IPEndPoint lep2 = new IPEndPoint(lipa.AddressList[0], 11001);
IPEndPoint lep3 = new IPEndPoint(lipa.AddressList[0], 11002);
//creates an array of endpoints.
IPEndPoint[] ipendpoints = new IPEndPoint[3];
ipendpoints[0] = lep1;
ipendpoints[1] = lep2;
ipendpoints[2] = lep3;
//Creates three separate sockets.
Socket s1 = new Socket(lep1.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
Socket s2 = new Socket(lep2.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
Socket s3 = new Socket(lep3.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
Socket[] socketList = new Socket[3];
socketList[0] = s1;
socketList[1] = s2;
socketList[2] = s3;
//Binds and Listens on all sockets in the array of sockets.
for (int i = 0; i < 3; i++){
socketList[i].Bind(ipendpoints[i]);
socketList[i].Listen(1000);
}
//Calls Select to determine which sockets are ready for reading.
Socket.Select(socketList, null, null, 1000);
//Reads on the sockets returned by Select.
byte[] buffer = new byte[1024];
for (int j=0; j < (socketList.Length-1); j++){
socketList[j].Receive(buffer);
Console.WriteLine("Socket " + j + " has the message" +
Encoding.ASCII.GetString(buffer));
}
Return to top Overloaded Method: Send( byte[] buffer ) Summary Sends data to a connected Socket, starting at the indicated location in the data. C# Syntax: public int Send( byte[] buffer ); Parameters: buffer The data to be sent. Return Value: The number of bytes sent to the Socket. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Use Socket.Send for connection-oriented protocols only. For connectionless protocols, either use Socket.SendTo or call Socket.Connect first, and then call Socket.Send. This overload only requires you to provide a data buffer. The offset defaults to 0, the size defaults to the buffer length, and SocketFlags value defaults to SocketFlags.None. You must set the Socket.LocalEndPoint property of the current instance before calling this method. Example The following example demonstrates sending data on a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
Return to top Overloaded Method: Send( byte[] buffer, SocketFlags socketFlags ) Summary Sends data to a connected Socket, starting at the indicated location in the data. C# Syntax: public int Send( byte[] buffer, SocketFlags socketFlags ); Parameters: buffer The data to be sent. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes sent to the Socket. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. ArgumentException The specified offset or size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Use Socket.Send for connection-oriented protocols only. For connectionless protocols, either use Socket.SendTo or call Socket.Connect first, and then call Socket.Send. This overload only requires you to provide a data buffer and SocketFlags. The offset defaults to 0, and the size parameter defaults to the buffer length. You must set the Socket.LocalEndPoint property of the current instance before calling this method. If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of the buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. Example The following example specifies the data buffer, and SocketFlags for sending data to a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
Return to top Overloaded Method: Send( byte[] buffer, int size, SocketFlags socketFlags ) Summary Sends data to a connected Socket, starting at the indicated location in the data. C# Syntax: public int Send( byte[] buffer, int size, SocketFlags socketFlags ); Parameters: buffer The data to be sent. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes sent to the Socket. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. ArgumentException The size parameter exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks Use Socket.Send for connection-oriented protocols only. For connectionless protocols, either use Socket.SendTo or call Socket.Connect first, and then call Socket.Send. This overload only requires you to provide a data buffer, SocketFlags, and the number bytes to be sent. The offset defaults to 0. You must set the Socket.LocalEndPoint property of the current instance before calling this method. If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of the buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. Example The following sends the data found in buffer, and specifies SocketFlags.None for SocketFlags.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, msg.Length, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, s.Available, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
Return to top Overloaded Method: Send( byte[] buffer, int offset, int size, SocketFlags socketFlags ) Summary Sends data to a connected Socket, starting at the indicated location in the data. C# Syntax: public int Send( byte[] buffer, int offset, int size, SocketFlags socketFlags ); Parameters: buffer The data to be sent. offset The position in the data buffer to begin sending data. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. Return Value: The number of bytes sent to the Socket. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. ArgumentOutOfRangeException The offset or size parameter exceeds the size of buffer. SocketException An operating system error occurs while accessing the socket. ObjectDisposedException The Socket has been closed. Remarks Use Socket.Send for connection-oriented protocols only. For connectionless protocols, either use Socket.SendTo or call Socket.Connect first, and then call Socket.Send. This overload gives you the flexibility to specify the Socket.Send starting position in the data buffer, the number bytes you are sending, and the necessary SocketFlags. You must set the Socket.LocalEndPoint property of the current instance before calling this method. If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of the buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. Example The following example specifies the data buffer, an offset, a size, and SocketFlags for sending data to a connected Socket.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg, 0, msg.Length, SocketFlags.None);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes, 0, s.Available, SocketFlags.None);
//Displays to the screen.
Console.WriteLine(Encoding.ASCII.GetString(bytes));
s.Shutdown(SocketShutdown.Both);
s.Close();
Return to top Overloaded Method: SendTo( byte[] buffer, EndPoint remoteEP ) Summary Sends data to a specific endpoint. C# Syntax: public int SendTo( byte[] buffer, EndPoint remoteEP ); Parameters: buffer The data to be sent. remoteEP The EndPoint representing the destination for the data. Return Value: The number of bytes sent. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null -or- The remoteEP parameter is null. ArgumentException The specified offset or size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you are using a connection-oriented protocol or a connected Socket using a connectionless protocol, remoteEP overrides the endpoint specified in Socket.RemoteEndPoint. If you are using an unconnected Socket with a connectionless protocol, this method sets the Socket.LocalEndPoint property of the current instance to a value determined by the protocol. You must subsequently receive data on the Socket.LocalEndPoint. This overload only requires you to provide a data buffer, and the remote EndPoint. The offset defaults to 0. The size defaults to the buffer length, and SocketFlags value defaults to SocketFlags.None. Example The following example sends a connectionless datagram to the specified remote host.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
Return to top Overloaded Method: SendTo( byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP ) Summary Sends data to a specific endpoint. C# Syntax: public int SendTo( byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP ); Parameters: buffer The data to be sent. socketFlags A bitwise combination of the SocketFlags values. remoteEP The EndPoint that represents the destination location for the data. Return Value: The number of bytes sent. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null -or- The remoteEP parameter is null. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you are using a connection-oriented protocol or a connected Socket using a connectionless protocol, remoteEP overrides the endpoint specified in Socket.RemoteEndPoint. If you are using an unconnected Socket with a connectionless protocol, this method sets the Socket.LocalEndPoint property of the current instance to a value determined by the protocol. You must subsequently receive data on the Socket.LocalEndPoint. This overload only requires you to provide a data buffer, SocketFlags, and the remote EndPoint. The offset defaults to 0, and size defaults to the buffer length. Note If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. If you are using a connection-oriented Socket, remoteEp is ignored. Example The following example sends a connectionless datagram to the specified remote host. SocketFlags are passed to the Socket.SendTo method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive themessage.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
Return to top Overloaded Method: SendTo( byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP ) Summary Sends data to a specific endpoint. C# Syntax: public int SendTo( byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP ); Parameters: buffer The data to be sent. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. remoteEP The EndPoint representing the destination location for the data. Return Value: The number of bytes sent. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. -or- The remoteEP parameter is null. ArgumentOutOfRangeException The specified size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you are using a connection-oriented protocol or a connected Socket using a connectionless protocol, remoteEP overrides the endpoint specified in Socket.RemoteEndPoint. If you are using an unconnected Socket with a connectionless protocol, this method sets the Socket.LocalEndPoint property of the current instance to a value determined by the protocol. You must subsequently receive data on the Socket.LocalEndPoint. This overload only requires you to provide a data buffer, SocketFlags, the number bytes to be sent and the remote EndPoint. The offset defaults to 0. Note If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. If you are using a connection-oriented Socket, remoteEp is ignored. Example The following example sends a connectionless datagram to the specified remote host. The size, and SocketFlags are passed to the Socket.SendTo method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, msg.Length, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, 100, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
Return to top Overloaded Method: SendTo( byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP ) Summary Sends data to a specific endpoint, starting at the indicated location in the data. C# Syntax: public int SendTo( byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP ); Parameters: buffer The data to be sent. offset The position in the data buffer to begin sending data. size The number of bytes to send. socketFlags A bitwise combination of the SocketFlags values. remoteEP The EndPoint representing the destination location for the data. Return Value: The number of bytes sent. Exceptions Exception Type Condition ArgumentNullException The buffer parameter is null. -or- The remoteEP parameter is null. ArgumentOutOfRangeException The specified offset or size exceeds the size of buffer. SocketException An operating system error occurs while accessing the Socket. ObjectDisposedException The Socket has been closed. Remarks If you are using a connection-oriented protocol or a connected Socket using a connectionless protocol, remoteEP overrides the endpoint specified in Socket.RemoteEndPoint. If you are using an unconnected Socket with a connectionless protocol, this method sets the Socket.LocalEndPoint property of the current instance to a value determined by the protocol. You must subsequently receive data on the Socket.LocalEndPoint. Note If you specify the SocketFlags.DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the SocketFlags.OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. If you set the Socket.Blocking property to true, and buffer space is not available within the underlying protocol, this method blocks. If you are using a message-oriented Socket, and the size of buffer is greater than the maximum message size of the underlying protocol, no data is sent and Socket will throw a SocketException. If you are using a connection-oriented Socket, remoteEp is ignored. Example The following example sends a connectionless datagram to the specified remote host. The offset, size, and SocketFlags are passed to the Socket.SendTo method.
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, 0, msg.Length, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, 0, 100, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen.
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine("Exception : " + e.ToString());
}
Return to top Overloaded Method: SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue ) Summary Sets the specified option to the specified value. C# Syntax: public void SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue ); Parameters: optionLevel A SocketOptionLevel value. optionName A SocketOptionName value. optionValue A byte array representing the value of the option. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. If using Win98 or WINNT4, this exception can also be thrown if you use SocketOptionName.AddMembership as the optionName parameter and don't call the Socket.Bind method first. ObjectDisposedException The Socket has been closed. Remarks Socket options determine the behavior of the current Socket. Use this overload to set those Socket options that require a byte array as an option value. Example The following example sets the LingerOption and Socket.Send time out values.
//Send operations will timeout of confirmation is not received within 1000 milliseconds.
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.SendTimeout, 1000);
//Socket will linger for 10 seconds after close is called.
LingerOption lingerOption = new LingerOption(true, 10);
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, lingerOption);
See also: SocketOptionName Return to top Overloaded Method: SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue ) Summary Sets the specified option to the specified value. C# Syntax: public void SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue ); Parameters: optionLevel A SocketOptionLevel value. optionName A SocketOptionName value. optionValue A value of the option. Exceptions Exception Type Condition SocketException An operating system error occurs while accessing the Socket. If using Win98 or WINNT4, this exception can also be thrown if you use SocketOptionName.AddMembership as the optionName and don't call the Socket.Bind method first. ObjectDisposedException The Socket has been closed. Remarks Socket options determine the behavior of the current Socket. For an option with a Boolean data type, specify a nonzero value to enable the option, and a zero value to disable the option. For an option with an integer data type, specify the appropriate value. Socket options are grouped by level of protocol support. Example The following example sets the LingerOption and Socket.Send time out values.
//Send operations will timeout of confirmation is not received within 1000 milliseconds.
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.SendTimeout, 1000);
//Socket will linger for 10 seconds after close is called.
LingerOption lingerOption = new LingerOption(true, 10);
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, lingerOption);
See also: SocketOptionName Return to top Overloaded Method: SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue ) Summary Sets the specified option to the specified value. C# Syntax: public void SetSocketOption( SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue ); Parameters: optionLevel A SocketOptionLevel value. optionName A SocketOptionName value. optionValue A LingerOption or MulticastOption containing the value of the option. Exceptions Exception Type Condition ArgumentNullException The optionValue parameter is null. SocketException An operating system error occurs while accessing the Socket. If using Win98 or WINNT4, this exception can also be thrown if you use SocketOptionName.AddMembership as the optionName and don't call the Socket.Bind method first. ObjectDisposedException The Socket has been closed. Remarks Socket options determine the behavior of the current Socket. Use this overload to set those Socket options that require anything other than an integer or Boolean as an option value. For example, to set the SocketOptionName.Linger option, you must create an instance of LingerOption and pass it to Socket.SetSocketOption as the optionvalue parameter. Example The following example sets the LingerOption and Socket.Send time out values.
//Send operations will timeout of confirmation is not received within 1000 milliseconds.
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.SendTimeout, 1000);
//Socket will linger for 10 seconds after close is called.
LingerOption lingerOption = new LingerOption(true, 10);
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, lingerOption);
See also: SocketOptionName Return to top Method: Shutdown( SocketShutdown how ) Summary Disables sends and receives on a Socket. C# Syntax: public void Shutdown(SocketShutdown( SocketShutdown how ); Parameters: how The SocketShutdown value specifying the operation that will no longer be allowed. Exceptions Exception Type Condition SocketException An error occurs while closing the Socket. ObjectDisposedException The Socket has been closed. Remarks The following table shows the SocketShutdown enumeration values that are valid for the how parameter. Value Description Send Disable sending on this Socket . Receive Disable receiving on this Socket . Both Disable both sending and receiving on this Socket . Setting how to SocketShutdown.Send, specifies that subsequent calls to Socket.Send are not allowed. With TCP sockets, a FIN will be sent after all data is sent and acknowledged by the receiver. Setting how to SocketShutdown.Receive, specifies that subsequent calls to Socket.Receive are not allowed. This has no effect on lower protocol layers. For TCP sockets, the connection is reset if data is waiting to be received or if more data arrives after the Socket is disabled. For UDP sockets, datagrams are accepted and queued. Setting how to SocketShutdown.Both disables both sends and receives as described above. To finish closing the Socket, a call to Socket.Close must be made after the call to Socket.Shutdown. You should not attempt to reuse the Socket. Example The following example uses Socket.Shutdown to disable the Socket.
aSocket.Shutdown(SocketShutdown.Both);
aSocket.Close();
if (aSocket.Connected) {
Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );
}
Return to top Method: ToString() Inherited See base class member description: System.Object.ToString C# Syntax: public virtual string ToString(); For more information on members inherited from System.Object click on the link above. Return to top Top of page Copyright (c) 2002 Microsoft Corporation. All rights reserved.