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

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.