< MemoryStream & NetworkStream Examples | Main | NetworkStream Sender Examples >

 


 

Chapter 2 Part 6:

Managed I/O - Streams, Readers, and Writers

 

 

What do we have in this chapter 2 Part 6?

  1. C++ NetworkStream Program Example – Receiver Program

  2. C# NetworkStream Program Example – Receiver Program

  3. VB .NET NetworkStream Program Example – Receiver Program

 

 

 

Note: If you want to experience a complete C++ .NET/C++-CLI programming tutorial please jump to Visual C++ .NET programming tutorial.

 

C++ NetworkStream Example – Receiver Program

 

Create a new CLR console application project and you might want to use NetworkStreamSampleCPReceiver as the project and solution names.

 

C++ NetworkStream Example – Receiver Program - CLR console application project example

 

Add the following code.

 

// NetworkStreamSampleCPReceiver.cpp : main project file.

// <summary>

// This sample demonstrates how to use the NetworkStream class to

// perform IO between 2 sockets. When using TCP Sockets you have to

// build a listening Socket application that will receive a connection

// from another application. In Socket terminology the application that

// receives a connection is know as a server and the peer that connects

// to a server is know as a client.

//

// The focus of this sample is not on Sockets but on network streams. We

// call this application a NetworkStreamServer because it is designed to

// receive a Socket connection and perform IO using a NetworkStream.

//

// To run this sample, simply just run the program without parameters and

// it will listen for a client connection on TCP port 5150. If you want to

// use a different port than 5150 then you can optionally supply a command

// line parameter "/port <port number>" and the listening socket will use your port instead.

// </summary>

 

#include "stdafx.h"

 

using namespace System;

using namespace System::Net;

using namespace System::Net::Sockets;

 

// <summary>

// The main entry point for the application.

// </summary>

[STAThread]

int main(array<System::String ^> ^args)

{

    // Change the address and port accordingly...

    String^ ServerName = "127.0.0.1";

    int Port = 5150;

 

    args = Environment::GetCommandLineArgs();

 

    // Parse command line arguments if any

    if(args->Length != 1)

    {

         for (int i = 0; i < args->Length; i++)

         {

                if (String::Compare(args[i], "/port", true) == 0)

            {

                // The port on which the server is listening

                Port = System::Convert::ToInt32(args[++i]->ToString());

            }

        }

     }

     // else display usage

     else

     {

               Console::WriteLine("Usage: {0} [/port <port number>]", args[0]);

               return 0;

    }

 

    Socket^ ServerSocket = nullptr;

    Socket^ ListeningSocket = nullptr;

 

    try

    {

        // Setup a listening Socket to await a connection from a peer socket.

        ListeningSocket = gcnew Socket(AddressFamily::InterNetwork, SocketType::Stream, ProtocolType::IP);

        IPEndPoint^ ListeningEndPoint = gcnew IPEndPoint(IPAddress::Parse(ServerName), Port);

        ListeningSocket->Bind(ListeningEndPoint);

        ListeningSocket->Listen(5);

 

        Console::WriteLine("Awaiting a TCP connection on IP:"

            + ListeningEndPoint->Address->ToString()

            + " Port:"

            + ListeningEndPoint->Port.ToString()

            + "...");

 

        ServerSocket = ListeningSocket->Accept();

 

         Console::WriteLine("Received a connection - awaiting data...");

    }

    catch (SocketException^ e)

    {

          Console::WriteLine("Failure to create Sockets: " + e->Message);

          return 0;

    }

    finally

    {

        // Close the listening socket - we do not plan to handle any additional connections.

        ListeningSocket->Close();

    }

 

    // Let's create a network stream to communicate over the connected Socket.

    NetworkStream^ ServerNetworkStream = nullptr;

 

    try

    {

        try

        {

            // Setup a network stream on the server Socket

            ServerNetworkStream = gcnew NetworkStream(ServerSocket, true);

        }

        catch (Exception^ e)

        {

            throw gcnew Exception("Failed to create a Network Stream with error: " + e->Message);

        }

 

        try

        {

            int BytesRead = 0;

            array< Byte >^ ReadBuffer = gcnew array< Byte >(4096);

 

            do

            {

                 BytesRead = ServerNetworkStream->Read(ReadBuffer, 0, ReadBuffer->Length);

                 Console::WriteLine("We read " + BytesRead.ToString() + " byte(s) from a peer socket.");

 

                for (int i = 0; i < BytesRead; i++)

                {

                    Console::WriteLine("The byte #" + i.ToString() + " contains " + ReadBuffer[i].ToString());

                }

            }

            while (BytesRead > 0);

        }

        catch (Exception^ e)

        {

            throw gcnew Exception("Failed to read from a network stream with error: " + e->Message);

        }

    }

    catch (Exception^ e)

    {

             Console::WriteLine(e->Message);

    }

    finally

    {

        // We are finished with the NetworkStream, so we will close it.

        // Note: the ServerSocket will be closed by the NetworkStream.

        ServerNetworkStream->Close();

    }

    return 0;

}

 

Build and run the project. The following is the output example when run at the Windows console/command prompt.

 

C++/CLI NetworkStream Example – Receiver Program - CLR console application project example - sample output

 

Let test the program with the sender program. In this case we use the NetworkStreamSampleCPSender program as the sender. Firstly, run the receiver program.

 

C++/CLI NetworkStream Example – Receiver Program - CLR console application project example - testing the output

 

Then, run the sender program. The following is the output sample.

 

C++/CLI NetworkStream Example – Receiver Program - CLR console application project example - sample sender/client output

 

The following is the output sample screenshot for the receiver when the communication was completed.

 

C++/CLI NetworkStream Example – Receiver Program - CLR console application project example - sample receiver/server output example

 

C# NetworkStream Example – Receiver Program

 

Create a new console application project. You can use the solution and project name as shown in the following Figure.

 

C# NetworkStream Example – Console application Receiver Program project example  

 

Add the following code.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net;

using System.Net.Sockets;

 

// <summary>

// This sample demonstrates how to use the NetworkStream class to

// perform IO between 2 sockets. When using TCP Sockets you have to

// build a listening Socket application that will receive a connection

// from another application. In Socket terminology the application that

// receives a connection is know as a server and the peer that connects

// to a server is know as a client.

//

// The focus of this sample is not on Sockets but on network streams. We

// call this application a NetworkStreamServer because it is designed to

// receive a Socket connection and perform IO using a NetworkStream.

//

// To run this sample, simply just run the program without parameters and

// it will listen for a client connection on TCP port 5150. If you want to

// use a different port than 5150 then you can optionally supply a command

// line parameter "/port <port number>" and the listening socket will use your port instead.

// </summary>

namespace NetworkStreamSampleCSReceiver

{

    class Program

    {

        // <summary>

        // The main entry point for the application.

        // </summary>

        [STAThread]

        static void Main(string[] args)

        {

            // Change the address and port accordingly...

            string ServerName = "127.0.0.1";

            int Port = 5150;

 

            // Parse command line arguments if any

            for (int i = 0; i < args.Length; i++)

            {

                try

                {

                    if (String.Compare(args[i], "/port", true) == 0)

                    {

                        // The port on which the server is listening

                        Port = System.Convert.ToInt32(args[++i].ToString());

                    }

                }

                catch (System.IndexOutOfRangeException)

                {

                    Console.WriteLine("Usage: " + args[0] + " [/port <port number>]");

                    return;

                }

            }

            Socket ServerSocket = null;

            Socket ListeningSocket = null;

 

            try

            {

                // Setup a listening Socket to await a connection from a peer socket.

                ListeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                IPEndPoint ListeningEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Port);

                ListeningSocket.Bind(ListeningEndPoint);

                ListeningSocket.Listen(5);

                Console.WriteLine("Awaiting a TCP connection on IP:"

                    + ListeningEndPoint.Address.ToString()

                    + " Port:"

                    + ListeningEndPoint.Port.ToString()

                    + "...");

 

                ServerSocket = ListeningSocket.Accept();

                Console.WriteLine("Received a connection - awaiting data...");

            }

            catch (SocketException e)

            {

                Console.WriteLine("Failure to create Sockets: " + e.Message);

                return;

            }

            finally

            {

                // Close the listening socket - we do not plan to handle any additional connections.

                ListeningSocket.Close();

            }

 

            // Let's create a network stream to communicate over the connected Socket.

            NetworkStream ServerNetworkStream = null;

 

            try

            {

                try

                {

                    // Setup a network stream on the server Socket

                    ServerNetworkStream = new NetworkStream(ServerSocket, true);

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create a Network Stream with error: " + e.Message);

                }

 

                try

                {

                    int BytesRead = 0;

                    byte[ ] ReadBuffer = new byte[4096];

 

                    do

                    {

                        BytesRead = ServerNetworkStream.Read(ReadBuffer, 0, ReadBuffer.Length);

                        Console.WriteLine("We read " + BytesRead.ToString() + " byte(s) from a peer socket.");

                        for (int i = 0; i < BytesRead; i++)

                        {

                            Console.WriteLine("The byte #" + i.ToString() + " contains " + ReadBuffer[i].ToString());

                        }

                    }

                    while (BytesRead > 0);

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to read from a network stream with error: " + e.Message);

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            finally

            {

                // We are finished with the NetworkStream, so we will close it.

                // Note: the ServerSocket will be closed by the NetworkStream.

                ServerNetworkStream.Close();

            }

        }

    }

}

 

An output sample:

 

C# NetworkStream Example – Console application Receiver Program project example - sample output

 

VB .NET NetworkStream Example – Receiver Program

 

Create a new console application project. You can use the solution and project name as shown in the following Figure.

 

VB .NET NetworkStream Example – Console Receiver Program project

 

Add the following code.

 

 

Imports System

Imports System.Net

Imports System.Net.Sockets

 

' This sample demonstrates how to use the NetworkStream class to

' perform IO between 2 sockets. When using TCP Sockets you have to

' build a listening Socket application that will receive a connection

' from another application. In Socket terminology the application that

' receives a connection is know as a server and the peer that connects

' to a server is know as a client.

'

' The focus of this sample is not on Sockets but on network streams. We

' call this application a NetworkStreamServer because it is designed to

' receive a Socket connection and perform IO using a NetworkStream.

'

' To run this sample, simply just run the program without parameters and

' it will listen for a client connection on TCP port 5150. If you want to

' use a different port than 5150 then you can optionally supply a command

' line parameter "/port <port number>" and the listening socket will use your port instead.

 

Module Module1

    ' The main entry point for the application.

    Sub Main()

        ' The following are default values, change accordingly

        Dim ServerName As String = "127.0.0.1"

        Dim Port As Integer = 5150

        ' Parse command line arguments if any

        Dim args As String() = Environment.GetCommandLineArgs()

        Dim i As Integer

 

        For i = 0 To args.Length - 1

            Try

                If args(i) = "/port" Then

                    ' The port on which the server is listening

                    i = i + 1

                    Port = System.Convert.ToInt32(args(i).ToString())

                End If

            Catch e As System.IndexOutOfRangeException

                Console.WriteLine("Usage: Receiver [/port <port number>]")

                Exit Sub

            End Try

        Next

 

        Dim ServerSocket As Socket = Nothing

        Dim ListeningSocket As Socket = Nothing

 

        Try

            ' Setup a listening Socket to await a connection from a peer socket.

            ListeningSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)

 

            Dim ListeningEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Parse(ServerName), Port)

 

            ListeningSocket.Bind(ListeningEndPoint)

            Console.WriteLine("Bind() is OK...")

            ListeningSocket.Listen(5)

            Console.WriteLine("Listen is OK...")

            Console.WriteLine("Awaiting a TCP connection on IP: " _

                                + ListeningEndPoint.Address.ToString() _

                                + " Port: " _

                                + ListeningEndPoint.Port.ToString() _

                                + "...")

            Console.WriteLine("Please run your sender program, I'm waiting...")

            ServerSocket = ListeningSocket.Accept()

            Console.WriteLine("Accept() is OK")

            Console.WriteLine("Received a connection - awaiting data...")

        Catch e As SocketException

            Console.WriteLine("Failure to create Sockets: " + e.Message)

            Exit Sub

        Finally

            ' Close the listening socket - we do not plan to handle any additional connections.

            ListeningSocket.Close()

        End Try

 

        ' Let's create a network stream to communicate over the connected Socket.

        Dim ServerNetworkStream As NetworkStream = Nothing

 

        Try

            Try

                ' Setup a network stream on the server Socket

                Console.WriteLine("Instantiate a NetworkStream object...")

                ServerNetworkStream = New NetworkStream(ServerSocket, True)

            Catch e As Exception

                Throw New Exception("Failed to create a Network Stream with error: " + e.Message)

            End Try

            Try

                Dim BytesRead As Integer = 0

                Dim ReadBuffer(4096) As Byte

 

                Console.WriteLine("Reading...")

                Do

                    BytesRead = ServerNetworkStream.Read(ReadBuffer, 0, ReadBuffer.GetUpperBound(0))

                    Console.WriteLine("We read " + BytesRead.ToString() + " byte(s) from a peer socket.")

                    For i = 0 To BytesRead - 1

                        Console.WriteLine("The byte #" + i.ToString() + " contains " + ReadBuffer(i).ToString())

                    Next

                Loop Until BytesRead > 0

            Catch e As Exception

                Throw New Exception("Failed to read from a network stream with error: " + e.Message)

            End Try

        Catch e As Exception

            Console.WriteLine(e.Message)

        Finally

            ' We are finished with the NetworkStream, so we will close it.

            ' Note: the ServerSocket will be closed by the NetworkStream.

            ServerNetworkStream.Close()

        End Try

    End Sub

End Module

 

An output sample:

 

VB .NET NetworkStream Example – Console Receiver Program project - receiver/server sample output

 

 

 


 

< MemoryStream & NetworkStream Examples | Main | NetworkStream Sender Examples >