public class Socket : IDisposable
|
The Socket class is used by the Microsoft .NET Framework to provide Internet connections to the TcpClient, UdpClient, and WebRequest and descendent classes.
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; }
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. |
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. |
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:
public Socket(AddressFamily addressFamily, Socket( |
addressFamily
socketType
protocolType
Exception Type | Condition |
---|---|
SocketException | The combination of addressFamily, socketType, and protocolType results in an invalid socket. |
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.
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 );
public AddressFamily AddressFamily {get;}
|
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());
public int Available {get;}
|
Exception Type | Condition |
---|---|
SocketException | An error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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();
public bool Blocking {get; set;}
|
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
Sockets are created in blocking mode by default. To set the Socket to not block, set Socket.Blocking to false.
public bool Connected {get;}
|
aSocket.Connect(anEndPoint); if (!aSocket.Connected) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())); }
public IntPtr Handle {get;}
|
public EndPoint LocalEndPoint {get;}
|
Exception Type | Condition |
---|---|
SocketException | An error occurs while reading the property. |
ObjectDisposedException | The Socket has been closed. |
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());
public ProtocolType ProtocolType {get;}
|
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());
public EndPoint RemoteEndPoint {get;}
|
Exception Type | Condition |
---|---|
SocketException | An error occurs while reading the property. |
ObjectDisposedException | The Socket has been closed. |
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());
public SocketType SocketType {get;}
|
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());
public Socket Accept(); |
Exception Type | Condition |
---|---|
SocketException | The Socket is invalid. |
ObjectDisposedException | The Socket has been closed. |
Socket mySocket = listeningSocket.Accept(); if (mySocket == null) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) ); }
public IAsyncResult BeginAccept( |
callback
state
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while creating the Socket. |
ObjectDisposedException | The Socket has been closed. |
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()); }
public IAsyncResult BeginConnect( |
remoteEP
callback
state
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. |
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()); }
public IAsyncResult BeginReceive( |
buffer
offset
size
socketFlags
callback
state
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. |
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);
public IAsyncResult BeginReceiveFrom( |
buffer
offset
size
socketFlags
remoteEP
callback
state
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. |
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()); }
public IAsyncResult BeginSend( |
buffer
offset
size
socketFlags
callback
state
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. |
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);
public IAsyncResult BeginSendTo( |
buffer
offset
size
socketFlags
remoteEP
callback
state
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. |
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()); }
public void Bind( |
localEP
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. |
try { aSocket.Bind(anEndPoint); } catch (Exception e) { Console.WriteLine("Winsock error: " + e.ToString()); }
public void Close(); |
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.
aSocket.Shutdown(SocketShutdown.Both); aSocket.Close(); if (aSocket.Connected) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) ); }
public void Connect( |
remoteEP
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. |
aSocket.Connect(anEndPoint); if (!aSocket.Connected) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())); }
protected virtual void Dispose( |
disposing
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.
public Socket EndAccept( |
asyncResult
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. |
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);
public void EndConnect( |
asyncResult
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. |
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);
public int EndReceive( |
asyncResult
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. |
The Socket.EndReceive method frees any resources allocated by the Socket.BeginReceive method.
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(); }
public int EndReceiveFrom( |
asyncResult
endPoint
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. |
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(); }
public int EndSend( |
asyncResult
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. |
The Socket.EndSend method frees any resources allocated by the Socket.BeginSend method.
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();
public int EndSendTo( |
asyncResult
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. |
The Socket.EndSendTo method frees any resources allocated by the Socket.BeginSendTo method.
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();
~Socket(); |
public override int GetHashCode(); |
public object GetSocketOption( |
optionLevel
optionName
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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();
public void GetSocketOption( |
optionLevel
optionName
optionValue
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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();
public byte[] GetSocketOption( |
optionLevel
optionName
optionLength
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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();
public Type GetType(); |
ioControlCode
optionInValue
optionOutValue
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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());
public void Listen( |
backlog
Exception Type | Condition |
---|---|
SocketException | An operating system error occurs while accessing the Socket. |
ObjectDisposedException | The Socket has been closed. |
// Allows a queue of 10 connections. aSocket.Listen(10); if (!aSocket.Connected) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())); }
protected object MemberwiseClone(); |
public bool Poll( |
microSeconds
mode
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. |
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. |
buffer
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. |
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.
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();
public int Receive( |
buffer
socketFlags
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. |
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.
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();
public int Receive( |
buffer
size
socketFlags
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. |
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.
// 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); }
public int Receive( |
buffer
offset
size
socketFlags
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. |
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.
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();
buffer
remoteEP
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. |
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.
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()); }
public int ReceiveFrom( |
buffer
socketFlags
remoteEP
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. |
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.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()); }
public int ReceiveFrom( |
buffer
size
socketFlags
remoteEP
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. |
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.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()); }
public int ReceiveFrom( |
buffer
offset
size
socketFlags
remoteEP
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. |
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.
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()); }
public static void Select( |
checkRead
checkWrite
checkError
microSeconds
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. |
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)); }
buffer
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. |
You must set the Socket.LocalEndPoint property of the current instance before calling this method.
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();
public int Send( |
buffer
socketFlags
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. |
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.
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();
public int Send( |
buffer
size
socketFlags
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. |
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.
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();
public int Send( |
buffer
offset
size
socketFlags
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. |
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.
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();
buffer
remoteEP
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. |
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()); }
public int SendTo( |
buffer
socketFlags
remoteEP
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. |
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.
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()); }
public int SendTo( |
buffer
size
socketFlags
remoteEP
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. |
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.
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()); }
public int SendTo( |
buffer
offset
size
socketFlags
remoteEP
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. |
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()); }
public void SetSocketOption( |
optionLevel
optionName
optionValue
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. |
//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);
public void SetSocketOption( |
optionLevel
optionName
optionValue
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. |
//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);
public void SetSocketOption( |
optionLevel
optionName
optionValue
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. |
//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);
public void Shutdown(SocketShutdown( |
how
Exception Type | Condition |
---|---|
SocketException | An error occurs while closing the Socket. |
ObjectDisposedException | The Socket has been closed. |
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.
aSocket.Shutdown(SocketShutdown.Both); aSocket.Close(); if (aSocket.Connected) { Console.WriteLine("Winsock error: " + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) ); }
public virtual string ToString(); |