How to control the transfer behavior when sending and receiving data on a Socket instance in C#

We can use the System.Net.Sockets SocketFlags Enumeration to control the transfer behavior when sending and receiving data on a Socket instance in C#.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketFlagsSample
{
    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, SocketFlags.Partial & SocketFlags.DontRoute);
                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

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.