< Raw Socket & IPv4, ICMP, TCP Listeners | Main | VB .NET TcpListener & C++ .NET TCP Client Examples >

 


 

Chapter 8 Part 28:

Client (and Server) Sockets Communication

 

 

What do we have in this chapter 8 Part 28?

  1. C++ TcpListener Program Example

  2. C# TcpListener Program Example

 

 

C++ TcpListener Program Example

 

Create a new CLR console application project and you might want to use TcpListenerSampleCP as the name.

 

C++ TcpListener Program Example - creating a new CLR console application project in VS 2008

 

 

Add the following code.

 

// TcpListenerSampleCP.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

using namespace System::Net;

using namespace System::Net::Sockets;

 

static void usage()

{

    Console::WriteLine("Usage: Executable_file_name [-l address] [-p port] [-x size]");

    Console::WriteLine("Available options:");

    Console::WriteLine("     -l address      Local address for TCP server to listen on");

    Console::WriteLine("     -p port         Local port for TCP server to listen on");

    Console::WriteLine("     -x size         Size of send and receive buffers");

    Console::WriteLine();

}

 

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

{

    IPAddress^ listenInterface = IPAddress::Any;

    unsigned short listenPort = 5150;

    int bufferSize = 4096;

 

    // Parse the command line

    if(args->Length !=0)

    {

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

    {

        try

        {

            if ((args[i][0] == '-') || (args[i][0] == '/'))

            {

                switch (Char::ToLower(args[i][1]))

                {

                    case 'l':       // Local interface server should listen on

                        listenInterface = IPAddress::Parse(args[++i]);

                        break;

 

                    case 'p':       // Port number for the destination

                        listenPort = Convert::ToUInt16(args[++i]);

                        break;

 

                    case 'x':       // Size of the send and receive buffers

                        bufferSize = Convert::ToInt32(args[++i]);

                        break;

 

                    default:

                        usage();

                        return 0;

                }

            }

        }

        catch(Exception^ err)

        {

            Console::WriteLine("Error: {0}", err->Message);

            usage();

            return 0;

        }

    }

}

else

{

      usage();

      return 0;

}

 

    TcpListener^ tcpServer = nullptr;

    TcpClient^ tcpClient = nullptr;

    NetworkStream^ tcpStream = nullptr;

    array<Byte>^ sendBuffer = gcnew array<Byte>(bufferSize);

    array<Byte>^ receiveBuffer = gcnew array<Byte>(bufferSize) ;

    array<Byte>^ byteCount;

    int bytesToRead = 0, nextReadCount, rc;

 

    // Initialize the send buffer

    Console::WriteLine("TCP Listener: Initializing the send buffer...");

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

        sendBuffer[i] = (Byte)'Y';

 

    try

    {

        // Create the TCP server

        Console::WriteLine("TCP Listener: Creating the TCP server...");

        tcpServer = gcnew TcpListener(listenInterface, (int)listenPort);

 

        Console::WriteLine("TCP Listener: TcpListener created on address {0} and port {1}",

        listenInterface->ToString(),

        listenPort

        );

 

        // Start listening for connections

        Console::WriteLine("TCP Listener: Start listening for connections...");

        tcpServer->Start();

 

        // Wait for a client connection

        Console::WriteLine("TCP Listener: Waiting for a client connection...");

        tcpClient = tcpServer->AcceptTcpClient();

 

        // Get the NetworkStream so we can do Read and Write on the client connection

        Console::WriteLine("TCP Listener: Getting the NetworkStream for reading/writing client connection...");

        tcpStream = tcpClient->GetStream();

 

        byteCount = BitConverter::GetBytes(bytesToRead);

 

        // First read the number of bytes the client is sending

        Console::WriteLine("TCP Listener: Reading the number of bytes client sent...");

        tcpStream->Read(byteCount, 0, byteCount->Length);

 

        bytesToRead = BitConverter::ToInt32(byteCount, 0);

 

        // Receive the data

        Console::WriteLine("TCP Listener: Receiving, reading & displaying the data...");

        while (bytesToRead > 0)

        {

            // Make sure we don't read beyond what the first message indicates

            //    This is important if the client is sending multiple "messages" --

            //    but in this sample it sends only one

            if (bytesToRead < receiveBuffer->Length)

                nextReadCount = bytesToRead;

            else

                nextReadCount = receiveBuffer->Length;

 

            // Read some data

            rc = tcpStream->Read(receiveBuffer, 0, nextReadCount);

 

            // Display what we read

            String^ readText = Text::Encoding::ASCII->GetString(receiveBuffer, 0, rc);

            Console::WriteLine("TCP Listener: Received: {0}", readText);

            bytesToRead -= rc;

        }

 

        // First send the number of bytes the server is responding with

        Console::WriteLine("TCP Listener: Sending the number of bytes the server is responding with...");

        byteCount = BitConverter::GetBytes(sendBuffer->Length);

        tcpStream->Write(byteCount, 0, byteCount->Length);

 

        // Send the actual data

        Console::WriteLine("TCP Listener: Sending the actual data...");

        tcpStream->Write(sendBuffer, 0, sendBuffer->Length);

 

        // Close up the client

        Console::WriteLine("TCP Listener: Closing client tcp stream...");

        tcpStream->Close();

        tcpStream = nullptr;

        tcpClient->Close();

        tcpClient = nullptr;

    }

    catch (SocketException^ err)

    {

        // Exceptions on the TcpListener are caught here

        Console::WriteLine("TCP Listener: Socket error occurred - {0}", err->Message);

    }

    catch (IO::IOException^ err)

    {

        // Exceptions on the NetworkStream are caught here

        Console::WriteLine("TCP Listener: I/O error: {0}", err->Message);

    }

    finally

    {

        // Close any remaining open resources

        if (tcpServer != nullptr)

            tcpServer->Stop();

        if (tcpStream != nullptr)

            tcpStream->Close();

        if (tcpClient != nullptr)

            tcpClient->Close();

    }

    return 0;

}

 

Next, build the project and make sure there is no error that can be seen in the Output window if any. Then, run the project. Any error will be thrown by the exception handlers. The following is the sample output.

 

C++ TcpListener Program Example - a sample output

 

Testing the tcp listener with the tcp client. In this case we use the TcpClientSampleCP program as a client. Firstly, we run the listener (both executables have been copied to the C:\).

 

C++ TcpListener Program Example - a sample output of the listener

 

Next, we run the client.

 

C++ TcpListener Program Example - a sample output, a client, sending and receiving data

 

The following is the tcp listener screenshot after the communication was completed.

 

C++ TcpListener Program Example - a sample output of the listener when the communication was completed

 

Well, you may want to test this program on real network with the listener and the client run on different hosts and try using the available options.

 

C# TcpListener Program Example

 

Create a new console application project and you might want to use TcpListenerSampleCS as the name.

 

C# TcpListener Program Example - a new console application project creation in VS 2008

 

Next, rename the class to SimpleTcpListener by renaming the source file name.

 

C# TcpListener Program Example - renaming the source file will automatically rename the class name  

 

Add/edit the following using directives at the top of the file.

 

using System;

using System.Net;

using System.Net.Sockets;

 

Next, add the usage() method and its code.

 

        static public void usage()

        {

            Console.WriteLine("Usage: Executable_file_name [-l address] [-p port] [-x size]");

            Console.WriteLine("Available options:");

            Console.WriteLine("     -l address      Local address for TCP server to listen on");

            Console.WriteLine("     -p port         Local port for TCP server to listen on");

            Console.WriteLine("     -x size         Size of send and receive buffers");

            Console.WriteLine();

        }

 

Then, add the Main() code.

 

        /// <param name="args">Command line arguments</param>

        static void Main(string[] args)

        {

            IPAddress listenInterface = IPAddress.Any;

            ushort listenPort = 5150;

            int bufferSize = 4096;

 

            usage();

 

            // Parse the command line

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

            {

                try

                {

                    if ((args[i][0] == '-') || (args[i][0] == '/'))

                    {

                        switch (Char.ToLower(args[i][1]))

                        {

                            case 'l':       // Local interface server should listen on

                                listenInterface = IPAddress.Parse(args[++i]);

                                break;

                            case 'p':       // Port number for the destination

                                listenPort = System.Convert.ToUInt16(args[++i]);

                                break;

                            case 'x':       // Size of the send and receive buffers

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

                                break;

                            default:

                                usage();

                                return;

                        }

                    }

                }

                catch

                {

                    usage();

                    return;

                }

            }

 

            TcpListener tcpServer = null;

            TcpClient tcpClient = null;

            NetworkStream tcpStream = null;

            byte[ ] sendBuffer = new byte[bufferSize], receiveBuffer = new byte[bufferSize], byteCount;

            int bytesToRead = 0, nextReadCount, rc;

 

            // Initialize the send buffer

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

                sendBuffer[i] = (byte)'Y';

 

            try

            {

                // Create the TCP server

                Console.WriteLine("TCP Listener: Creating the TCP server...");

                tcpServer = new TcpListener(listenInterface, (int)listenPort);

                Console.WriteLine("TCP Listener: TcpListener created on address {0} and port {1}",

                    listenInterface.ToString(),

                    listenPort

                    );

 

                // Start listening for connections

                Console.WriteLine("TCP Listener: Start listening for connections...");

                tcpServer.Start();

 

                // Wait for a client connection

                Console.WriteLine("TCP Listener: Waiting for a client connection...");

                tcpClient = tcpServer.AcceptTcpClient();

 

                // Get the NetworkStream so we can do Read and Write on the client connection

                Console.WriteLine("TCP Listener: Getting the NetworkStream for reading/writing client connection...");

                tcpStream = tcpClient.GetStream();

 

                byteCount = BitConverter.GetBytes(bytesToRead);

 

                // First read the number of bytes the client is sending

                Console.WriteLine("TCP Listener: Reading the number of bytes client sent...");

                tcpStream.Read(byteCount, 0, byteCount.Length);

 

                bytesToRead = BitConverter.ToInt32(byteCount, 0);

 

                // Receive the data

                Console.WriteLine("TCP Listener: Receiving, reading & displaying the data...");

                while (bytesToRead > 0)

                {

                    // Make sure we don't read beyond what the first message indicates

                    //    This is important if the client is sending multiple "messages" --

                    //    but in this sample it sends only one

                    if (bytesToRead < receiveBuffer.Length)

                        nextReadCount = bytesToRead;

                    else

                        nextReadCount = receiveBuffer.Length;

 

                    // Read some data

                    rc = tcpStream.Read(receiveBuffer, 0, nextReadCount);

 

                    // Display what we read

                    string readText = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, rc);

                    Console.WriteLine("TCP Listener: Received: {0}", readText);

                    bytesToRead -= rc;

                }

 

                // First send the number of bytes the server is responding with

                Console.WriteLine("TCP Listener: Sending the number of bytes the server is responding with...");

                byteCount = BitConverter.GetBytes(sendBuffer.Length);

                tcpStream.Write(byteCount, 0, byteCount.Length);

 

                // Send the actual data

                Console.WriteLine("TCP Listener: Sending the actual data...");

                tcpStream.Write(sendBuffer, 0, sendBuffer.Length);

 

                // Close up the client

                Console.WriteLine("TCP Listener: Closing client tcp stream...");

                tcpStream.Close();

                tcpStream = null;

                tcpClient.Close();

                tcpClient = null;

            }

            catch (SocketException err)

            {

                // Exceptions on the TcpListener are caught here

                Console.WriteLine("TCP Listener: Socket error occurred: {0}", err.Message);

            }

            catch (System.IO.IOException err)

            {

                // Exceptions on the NetworkStream are caught here

                Console.WriteLine("TCP Listener: I/O error: {0}", err.Message);

            }

            finally

            {

                // Close any remaining open resources

                if (tcpServer != null)

                    tcpServer.Stop();

                if (tcpStream != null)

                    tcpStream.Close();

                if (tcpClient != null)

                    tcpClient.Close();

            }

        }

 

Next, build the project and make sure there is no error that can be seen in the Output window if any.

 

C# TcpListener Program Example - building the project

 

Then, run the project. Any error will be thrown by the exception handlers.

 

C# TcpListener Program Example - running the project with default argument values

 

The following is the sample output.

 

C# TcpListener Program Example - a sample output, the TCP listener is waiting client connections

 

Testing the tcp listener with the tcp client. In this case we use the TcpClientSampleCS program as a client. Firstly, we run the listener (both executables have been copied to the C:\).

 

C# TcpListener Program Example - running the TCP listener

 

Next, we run the client.

 

C# TcpListener Program Example - running the TCP client, connecting to the TCP listener

 

The following is the tcp listener screenshot after the communication was completed.

 

C# TcpListener Program Example - the TCP listener screen when the communication was completed

 

Well, you may want to test this program on real network with the listener and the client run on different hosts and try using the available options.

 

 

 


 

< Raw Socket & IPv4, ICMP, TCP Listeners | Main | VB .NET TcpListener & C++ .NET TCP Client Examples >