How to specify the mode used by the Poll method of the Socket class in C#
We can use the System.Net.Sockets SelectMode Enum to specify the mode used by the Poll method of the Socket class in C#. A SelectMode member specifies the status information (read, write, or error) to retrieve from the current Socket instance.
using System; using System.Net; using System.Net.Sockets; using System.Text; public class SelectModeSample { private static void ShowSelectMode(Socket skt) { if (skt.Poll(1000, SelectMode.SelectRead) == true) Console.WriteLine(" - You can read from this Socket"); if(skt.Poll(1000, SelectMode.SelectWrite) == true) Console.WriteLine(" - You can write to this Socket"); if (skt.Poll(1000, SelectMode.SelectError)) Console.WriteLine(" - There was an error connecting"); } public static void Main() { IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint ep = new IPEndPoint(ip, 80); Console.WriteLine("Opening connection..."); skt.Connect(ep); ShowSelectMode(skt); Console.WriteLine("Sending request..."); string targ = "/default.htm"; Byte[] req = Encoding.ASCII.GetBytes("GET " + targ + "\n"); skt.Send(req); Console.WriteLine("Awaiting response..."); Byte[] res = new Byte[512]; int rec = skt.Receive(res); ShowSelectMode(skt); Console.WriteLine("Received {0} bytes for {1}:", rec, targ); Console.WriteLine(Encoding.ASCII.GetString(res, 0, rec)); skt.Shutdown(SocketShutdown.Both); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { skt.Close(); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } }
Output:
Opening connection…
- You can write to this Socket
Sending request…
Awaiting response…
- You can read from this Socket
- You can write to this Socket
Received 60 bytes for /default.htm:
<html>
<body>
This is the default page
</body>
</html>
Press Enter to continue
How to specify the protocol to be used by the Socket class in C#
The System.Net.Sockets ProtocolType Enum class can be used to specify the protocol to be used by the Socket class in C#. The ProtocolType enumeration is used with the Socket class. This enumeration specifies the protocols that a socket instance can use to transport data.
using System; using System.Net; using System.Net.Sockets; using System.Text; public class ProtocolTypeSample { public static void Main() { IPAddress ip = IPAddress.Parse("127.0.0.1"); string targ = "/default.htm"; Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint ep = new IPEndPoint(ip, 80); skt.Connect(ep); if (skt.Connected) { Byte[] req = Encoding.ASCII.GetBytes("GET " + targ + "\n"); skt.Send(req); Byte[] res = new Byte[1024]; int rec = skt.Receive(res); skt.Shutdown(SocketShutdown.Both); Console.WriteLine("Received {0} bytes for {1}:", rec, targ); Console.WriteLine(Encoding.ASCII.GetString(res, 0, rec)); } else { Console.WriteLine("Cannot connect to host {0}", ip); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { skt.Close(); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } }
Output:
Received 60 bytes for /default.htm:
<html>
<body>
This is the default page
</body>
</html>
Press Enter to continue
NetworkStream in C# Socket
The NetworkStream class implements the standard stream mechanism to read and write network data through an instance of the Socket class. The NetworkStream class allows network data to be read and written in the same manner as the System.IO.Stream class. This class supports simultaneous synchronous and asynchronous access to the network data. Random access is not supported and thus the CanSeek property always returns false.
Example
using System; using System.Net; using System.Net.Sockets; using System.Text; public class NetworkStreamSample { private static bool bDone = false; private static Socket skt = null; private static NetworkStream ns = null; private static Byte[] res = new Byte[1024]; public static void Main() { try { skt = GetConnectedSocket(); ns = new NetworkStream(skt, true); string targ = "/default.htm"; byte[] req = Encoding.ASCII.GetBytes("GET " + targ + "\n"); ns.Write(req, 0, req.Length); ns.BeginRead(res, 0 ,res.Length, new AsyncCallback(ReadHandler), null); Console.WriteLine("BeginRead completed..."); while(!bDone) {} } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { ns.Close(); skt.Close(); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } private static Socket GetConnectedSocket() { IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint ep = new IPEndPoint(ip, 80); skt.Connect(ep); if (skt.Connected) { return skt; } else { throw new Exception("Cannot connect to host " + ip); } } catch (Exception e) { throw e; } } private static void ReadHandler(IAsyncResult ar) { try { Console.WriteLine("ReadHandler executing..."); int rec = ns.EndRead(ar); Console.WriteLine("Received {0} bytes", rec); Console.WriteLine(Encoding.ASCII.GetString(res, 0, rec)); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { ns.Close(); bDone = true; } } }
Output:
BeginRead completed…
ReadHandler executing…
Received 60 bytes
<html>
<body>
This is the default page
</body>
</html>
Press Enter to continue
MulticastOption in C# socket
The MulticastOption contains Internet Protocol (IP) addresses used when joining or leaving an IP multicast group. The hosts listening to a specific IP multicast address (the group address) are called a multicast group. Each member of the group receives any IP messages sent to the group address.
Type Summary:
public class MulticastOption { // Constructors public MulticastOption(IPAddress group); public MulticastOption(IPAddress group, IPAddress mcint); // Properties public IPAddress Group { get; set; } public IPAddress LocalAddress { get; set; } }
LingerOption in C# sockets
The LingerOption maintains information that specifies how a Socket instance with pending data behaves when the Close method of the socket is called. When the Enabled property is true, any queued data continues to be sent until time equal to the setting of the LingerTime property has passed or until the input queue is empty. At this time, the connection is closed.
using System; using System.Net; using System.Net.Sockets; using System.Text; public class LingerOptionSample { public static void Main() { LingerOption lo = new LingerOption(true, 5); TestLinger(lo); lo.Enabled = false; TestLinger(lo); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } private static void TestLinger(LingerOption lo) { IPAddress ip = IPAddress.Parse("127.0.0.1"); IPEndPoint ep = new IPEndPoint(ip, 80); Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); skt.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo); Console.Write("LingerOption.Enabled = {0} ... ", lo.Enabled); try { skt.Connect(ep); Byte[] req = Encoding.ASCII.GetBytes("Test"); skt.SendTo(req, ep); skt.Shutdown(SocketShutdown.Both); Console.WriteLine("Request sent."); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { skt.Close(); } } }
Output:
LingerOption.Enabled = True … Request sent.
LingerOption.Enabled = False … Request sent.
Press Enter to continue
AddressFamily in C# Sockets
The AddressFamily specifies the addressing schemes used by the Socket class in C#.
using System; using System.Net; using System.Net.Sockets; using System.Text; public class AddressFamilySample { public static void Main() { IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { IPEndPoint ep = new IPEndPoint(ip, 9999); skt.Connect(ep); Byte[] req = Encoding.ASCII.GetBytes("Test"); skt.SendTo(req, ep); IPEndPoint rep = (IPEndPoint)skt.LocalEndPoint; Console.WriteLine("LocalEndPoint details:"); Console.WriteLine("Address: {0}", rep.Address); Console.WriteLine("AddressFamily: {0}", rep.AddressFamily); Console.WriteLine("Port: {0}", rep.Port); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } finally { skt.Close(); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } }
Output:
LocalEndPoint details:
Address: 127.0.0.1
AddressFamily: InterNetwork
Port: 4082
