< NetworkStream Receiver Examples | Main | Composable & BufferedStream Streams >

 


 

Chapter 2 Part 7:

Managed I/O - Streams, Readers, and Writers

 

 

What do we have in this chapter 2 Part 7?

  1. C++ NetworkStream Program Example – Sender Program

  2. C# NetworkStream Program Example – Sender Program

  3. VB .NET NetworkStream Program Example – Sender 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 – Sender Program

 

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

 

C++/CLI NetworkStream Example – Sender Program

 

Add the following code and you can omit the comments.

 

// NetworkStreamSampleCPSender.cpp : main project file.

 

// <summary>

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

// perform IO between 2 sockets. Typically sockets will communicate

// across a network to foster communication between processes.

// This application is designed to create a socket that can connect to the

// Receiver application. Once the receiver accepts our connection, we can

// create a network stream to send data over the socket.

//

// This sample has 2 optional parameters that can be used:

// Sender [/server <server IP>] [/port <port>]

// By default this application will connect to the server on the same machine using TCP port 5150.

// </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)

{

    // default host and port used...

    String^ ServerName = "127.0.0.1";

    int Port = 5150;

 

            args = Environment::GetCommandLineArgs();

          

            if(args->Length != 1)

            {

                        // Parse command line arguments if any

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

                        {

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

                                    {

                                                // The server's name we will connect to

                                                ServerName = args[++i]->ToString();

                                     }

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

                                     {

                                                // The port on which the server is listening

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

                                     }

                        }

            }

        else

        {

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

            return 0;

        }

 

    Socket^ ClientSocket = nullptr;

 

    try

    {

        // Let's connect to a listening server

        try

        {

              Console::WriteLine("Creating a client Socket...");

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

        }

        catch (Exception^ e)

        {

            Console::Write("Failed to create client Socket: \n ");

            throw gcnew Exception(e->Message);

        }

 

        IPEndPoint^ ServerEndPoint = gcnew IPEndPoint(IPAddress::Parse(ServerName), Convert::ToInt16(Port));

 

        try

        {

             ClientSocket->Connect(ServerEndPoint);

             Console::WriteLine("Connect() is OK, connecting to {0} at {1}...", ServerName, Port);

        }

        catch (Exception^ e)

        {

            Console::Write("Failed to create client Socket: \n  ");

            throw gcnew Exception(e->Message);

        }

    }

    catch (Exception^ e)

    {

        Console::WriteLine(e->Message);

        Console::WriteLine("Closing the Socket...");

        ClientSocket->Close();

        return 0;

    }

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

    NetworkStream^ ClientNetworkStream = nullptr;

    try

    {

        try

        {

            // Setup a network stream on the client Socket

            Console::WriteLine("Instantiate NetworkStream object for communication...");

            ClientNetworkStream = gcnew NetworkStream(ClientSocket, true);

        }

        catch (Exception^ e)

        {

            // We have to close the client socket here because the network stream did not take ownership of the socket.

            ClientSocket->Close();

            throw gcnew Exception("Failed to create a NetworkStream with error: \n" + e->Message);

        }

 

        try

        {

            array< Byte >^ Buffer = gcnew array< Byte >(1);

 

            Console::WriteLine("Writing/sending integers 0 - 200...");

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

            {

                Buffer[0] = (Byte)i;

                ClientNetworkStream->Write(Buffer, 0, Buffer->Length);

            }

                 Console::WriteLine("We wrote 200 bytes to the server...");

        }

        catch (Exception^ e)

        {

            throw gcnew Exception("Failed to write to client NetworkStream with error: " + e->Message);

        }

    }

    catch (Exception^ e)

    {

              Console::WriteLine(e->Message);

    }

    finally

    {

        // Close the network stream once everything is done

        Console::WriteLine("Closing the NetworkStream...");

        ClientNetworkStream->Close();

    }

    return 0;

}

 

Build and run the project. The following is the output example.

 

C++/CLI NetworkStream Example – Sender Program - sample output

 

Let test this program with the receiver program. In this case we use NetworkStreamSampleCPReceiver. Firstly, run the receiver program.

 

C++/CLI NetworkStream Example – Server/receiver program output sample

 

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

 

C++/CLI NetworkStream Example – Sender Program output sample

 

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

 

C++/CLI NetworkStream Example – Receiver/server program output example

 

C# NetworkStream Example – Sender Program

 

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

 

C# NetworkStream Example – Sender Program

 

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. Typically sockets will communicate

// across a network to foster communication between processes.

// This application is designed to create a socket that can connect to the

// Receiver application. Once the receiver accepts our connection, we can

// create a network stream to send data over the socket.

//

// This sample has 2 optional parameters that can be used:

// Sender [/server <server IP>] [/port <port>]

// By default this application will connect to the server on the same machine using TCP port 5150.

//

// </summary>

namespace NetworkStreamSampleCSSender

{

    class Program

    {

        // <summary>

        // The main entry point for the application.

        // </summary>

        [STAThread]

        static void Main(string[ ] args)

        {

            // default host and port used if not supplied by user...

            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], "/server", true) == 0)

                    {

                        // The server's name we will connect to

                        ServerName = args[++i].ToString();

                    }

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

                    {

                        // The port on which the server is listening

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

                    }

                }

                catch (IndexOutOfRangeException)

                {

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

                    return;

                }

            }

            Socket ClientSocket = null;

 

            try

            {

                // Let's connect to a listening server

                try

                {

                    Console.WriteLine("Creating a client Socket...");

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

                }

                catch (Exception e)

                {

                    Console.Write("Failed to create client Socket: ");

                    throw new Exception(e.Message);

                }

                IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port));

 

                try

                {

                    ClientSocket.Connect(ServerEndPoint);

                    Console.WriteLine("Connect() is OK, connecting to " + ServerName + " at " + Port + "...");

                }

                catch (Exception e)

                {

                    Console.Write("Failed to create client Socket: ");

                    throw new Exception(e.Message);

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

                Console.WriteLine("Closing the Connect()...");

                ClientSocket.Close();

                return;

            }

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

            NetworkStream ClientNetworkStream = null;

            try

            {

                try

                {

                    // Setup a network stream on the client Socket

                    Console.WriteLine("Instantiate NetworkStream object for communication...");

                    ClientNetworkStream = new NetworkStream(ClientSocket, true);

                }

                catch (Exception e)

                {

                    // We have to close the client socket here because the network stream did not take ownership of the socket.

                    ClientSocket.Close();

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

                }

 

                try

                {

                    byte[ ] Buffer = new byte[1];

 

                    Console.WriteLine("Writing/sending integers 0 - 200...");

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

                    {

                        Buffer[0] = (byte)i;

                        ClientNetworkStream.Write(Buffer, 0, Buffer.Length);

                    }

                    Console.WriteLine("We wrote 200 bytes to the server.");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to write to client NetworkStream with error: " + e.Message);

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            finally

            {

                // Close the network stream once everything is done

                Console.WriteLine("Closing the NetworkStream...");

                ClientNetworkStream.Close();

            }

        }

    }

}

 

An output sample:

 

C# NetworkStream Example – Sender Program - sample sender/client output  

 

Next, let execute both programs. Firstly, run the receiver program and then the sender program. Make sure the IP address and port number are match. The following is a sample output.

 

C# NetworkStream Example – Receiver/server and client/sender in action

 

VB .NET NetworkStream Example – Sender 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 – Sender Program

 

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. Typically sockets will communicate

' across a network to foster communication between processes.

' This application is designed to create a socket that can connect to the

' Receiver application. Once the receiver accepts our connection, we can

' create a network stream to send data over the socket.

'

' This sample has 2 optional parameters that can be used:

' Sender [/server <server IP>] [/port <port>]

' By default this application will connect to the server on the same machine

' using TCP port 5150.

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) = "/server" Then

                    ' The server's name we will connect to

                    i = i + 1

                    ServerName = args(i).ToString()

 

                ElseIf 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: Sender [/server <server IP>] [/port <port>]")

                Exit Sub

            End Try

        Next

 

        Dim ClientSocket As Socket = Nothing

 

        Try

            ' Let's connect to a listening server

            Try

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

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

            Catch e As Exception

                Throw New Exception("Failed to create client Socket: " + e.Message)

            End Try

 

            Dim ServerEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port))

 

            Try

                ClientSocket.Connect(ServerEndPoint)

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

            Catch e As Exception

                Throw New Exception("Failed to connect client Socket: " + e.Message)

            End Try

 

        Catch e As Exception

            Console.WriteLine(e.Message)

            ClientSocket.Close()

            Exit Sub

        End Try

 

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

        Dim ClientNetworkStream As NetworkStream = Nothing

 

        Try

            Try

                ' Setup a network stream on the client Socket

                ClientNetworkStream = New NetworkStream(ClientSocket, True)

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

            Catch e As Exception

                ' We have to close the client socket here because the network stream did not take ownership of the socket.

                ClientSocket.Close()

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

            End Try

            Try

                Dim Buffer(1) As Byte

                Console.WriteLine("Sending/writing some bytes...")

                For i = 1 To 200

                    Buffer(0) = i

                    ClientNetworkStream.Write(Buffer, 0, Buffer.GetUpperBound(0))

                Next

                Console.WriteLine("We wrote 200 bytes to the server.")

            Catch e As Exception

                Throw New Exception("Failed to write to client NetworkStream with error: " + e.Message)

            End Try

        Catch e As Exception

            Console.WriteLine(e.Message)

        Finally

            ' Close the network stream once everything is done

            ClientNetworkStream.Close()

        End Try

    End Sub

End Module

 

An output sample:

 

VB .NET NetworkStream Example – Sender Program output sample

 

When running both the sender and the receiver programs, the following is the sample output.

 

VB .NET NetworkStream Example – Sender and receiver Program in action

 

 

 


 

< NetworkStream Receiver Examples | Main | Composable & BufferedStream Streams >