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

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.