< VB .NET TcpListener & C++ .NET TCP Client Examples | Main | C++ and C# UDP Client & Server Examples >


 

Chapter 8 Part 30:

Client (and Server) Sockets Communication

 

 

What do we have in this chapter 8 Part 30?

  1. C# TCP Client Program Example

  2. VB .NET TCP Client Program Example

 

C# TCP Client Program Example

 

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

 

C# TCP Client Program Example - creating a new console application project in VS 2008 IDE

 

 

Next, rename the class to TcpClientSample by renaming the source file.

 

C# TCP Client 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;

 

Add the following method for the TcpClientSample class.

 

/// <summary>

/// Displays simple usage information.

/// </summary>

static public void usage()

{

            Console.WriteLine("usage: TcpClientSample.exe [-n server] [-p port] [-x size]");

            Console.WriteLine("Available options:");

            Console.WriteLine("     -n server       Name or address of server to connect to");

            Console.WriteLine("     -p port         Port number to connect to server on");

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

            Console.WriteLine();

}

 

Next, add the Main() code.

 

static void Main(string[ ] args)

        {

            // Initial/default values

            string serverAddress = "localhost";

            ushort serverPort = 5150;

            int bufferSize = 1024;

 

            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 'n':       // String name or address of server to connect to

                                serverAddress = args[++i];

                                break;

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

                                serverPort = 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;

                }

            }

 

            TcpClient simpleTcp = null;

            NetworkStream tcpStream = null;

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

            int bytesToRead = 0, nextReadCount, rc;

 

            // Initialize the send buffer

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

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

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

 

            try

            {

                // Create the client and indicate the server to connect to

                Console.WriteLine("TCP client: Creating the client and indicate the server to connect to...");

                simpleTcp = new TcpClient(serverAddress, (int)serverPort);

 

                // Retrieve the NetworkStream so we can do Read and Write

                Console.WriteLine("TCP client: Retrieving the NetworkStream so we can do Read and Write...");

                tcpStream = simpleTcp.GetStream();

 

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

                Console.WriteLine("TCP client: Sending the number of bytes the client is sending...");

                byteCount = BitConverter.GetBytes(sendBuffer.Length);

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

 

                // Send the actual data

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

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

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

 

                // Read how many bytes the server is responding with

                Console.WriteLine("TCP client: Reading how many bytes the server is responding with...");

                bytesToRead = BitConverter.ToInt32(byteCount, 0);

 

                // Receive the data

                Console.WriteLine("TCP client: 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 the data

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

 

                    // Display what was read

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

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

                    bytesToRead -= rc;

                }

            }

            catch (SocketException err)

            {

                // Exceptions on the TcpListener are caught here

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

            }

            catch (System.IO.IOException err)

            {

                // Exceptions on the NetworkStream are caught here

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

            }

            finally

            {

                // Close any remaining open resources

                Console.WriteLine("TCP client: Closing all the opening resources...");

                if (tcpStream != null)

                    tcpStream.Close();

                if (simpleTcp != null)

                    simpleTcp.Close();

            }

        }

 

 

 

 

Next, build the project and make sure there is no error.

 

C# TCP Client Program Example - building the project

 

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

 

C# TCP Client Program Example - running the project

 

The following is the sample output.

 

C# TCP Client Program Example - a sample output of the TCP client in action

 

The following are sample outputs when run at the command prompt for tcp listener and tcp client. The listener program used is the previously created, TcpListenerSampleCS.exe. Firstly, we run the listener. The listener is waiting a connection from client.

 

C# TCP Client Program Example - running the TCP listener to test the TCP client. TCP listener is waiting client connections

 

Then we run the tcp client.

 

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

 

The following is the tcp listener output screenshot when the communication was completed.

 

C# TCP Client Program Example - the TCP listener screen when the communication with the TCP client was completed

 

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

 

VB .NET TCP Client Program Example

 

Create a new class library project and you might want to use TcpClientSampleVB as the name.

 

VB .NET TCP Client Program Example - creating a new class library project in Visual Studio 2008 IDE

 

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

 

VB .NET TCP Client Program Example - renaming the class to reflect the application to be developed

 

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

 

Imports System

Imports System.Net

Imports System.Net.Sockets

 

Next, add the usage() subroutine code

 

' Displays simple usage information.       

    Shared Sub usage()

        Console.WriteLine("Usage: TcpClientSampleVB [-n server] [-p port] [-x size]")

        Console.WriteLine("Available options:")

        Console.WriteLine("     -n server       Name or address of server to connect to")

        Console.WriteLine("     -p port         Port number to connect to server on")

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

        Console.WriteLine()

    End Sub

 

Then, add the Main() subroutine code.

 

Shared Sub Main()

        Dim serverAddress As String = "localhost"

        Dim serverPort As Short = 5150

        Dim bufferSize As Integer = 1024

 

        ' Parse the command line

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

        Dim i As Integer

 

        usage()

 

        For i = 1 To args.GetUpperBound(0)

            Try

                Dim CurArg() As Char = args(i).ToCharArray(0, args(i).Length)

                If (CurArg(0) = "-") Or (CurArg(0) = "/") Then

                    Select Case Char.ToLower(CurArg(1), System.Globalization.CultureInfo.CurrentCulture)

                        Case "n" ' String name or address of server to connect to

                            i = i + 1

                            serverAddress = args(i)

                        Case "p" ' Port number for the destination

                            i = i + 1

                            serverPort = System.Convert.ToInt16(args(i))

                        Case "x"       ' Size of the send and receive buffers

                            i = i + 1

                            bufferSize = System.Convert.ToInt32(args(i))

                        Case Else

                            usage()

                            Exit Sub

                    End Select

                End If

 

            Catch e As Exception

                usage()

                Exit Sub

            End Try

        Next

 

        Dim simpleTcp As TcpClient = Nothing

        Dim tcpStream As NetworkStream = Nothing

        Dim sendBuffer(bufferSize) As Byte

        Dim receiveBuffer(bufferSize) As Byte

        Dim byteCount() As Byte

        Dim bytesToRead As Integer = 0

        Dim nextReadCount, rc As Integer

 

        ' Initialize the send buffer

        Console.WriteLine("Initializing the send buffer...")

        For i = 0 To sendBuffer.GetUpperBound(0) - 1

            sendBuffer(i) = CByte(65)

        Next

 

        Try

            ' Create the client and indicate the server to connect to

            Console.WriteLine("Creating the client and indicate the server to connect to...")

            simpleTcp = New TcpClient(serverAddress, serverPort)

 

            ' Retrieve the NetworkStream so we can do Read and Write

            Console.WriteLine("Retrieving the NetworkStream so we can do Read and Write...")

            tcpStream = simpleTcp.GetStream()

 

            ' First send the number of bytes the client is sending

            Console.WriteLine("Sending the number of bytes...")

            byteCount = BitConverter.GetBytes(sendBuffer.GetUpperBound(0))

            tcpStream.Write(byteCount, 0, byteCount.GetUpperBound(0))

 

            ' Send the actual data

            Console.WriteLine("Sending the actual data...")

            tcpStream.Write(sendBuffer, 0, sendBuffer.GetUpperBound(0))

            tcpStream.Read(byteCount, 0, byteCount.GetUpperBound(0))

 

            ' Read how many bytes the server is responding with

            Console.WriteLine("Reading how many bytes the server is responding with...")

            bytesToRead = BitConverter.ToInt32(byteCount, 0)

 

            ' Receive the data

            Console.WriteLine("Receive, read & display 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.GetUpperBound(0)) Then

                    nextReadCount = bytesToRead

                Else

                    nextReadCount = receiveBuffer.GetUpperBound(0)

                End If

 

                ' Read the data

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

 

                ' Display what was read

                Dim readText As String = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, rc)

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

                bytesToRead -= rc

            End While

 

        Catch err As SocketException

            ' Exceptions on the TcpListener are caught here

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

 

        Catch err As System.IO.IOException

            ' Exceptions on the NetworkStream are caught here

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

 

        Finally

            ' Close any remaining open resources

            Console.WriteLine("Closing any remaining open resources...")

            If (Not IsNothing(tcpStream)) Then

                tcpStream.Close()

            End If

 

            If (Not IsNothing(simpleTcp)) Then

                simpleTcp.Close()

            End If

        End Try

    End Sub

 

We need to change the DLL to EXE type program so that we can run it n console mode. Select the project folder > Right click mouse > Select Properties context menu.

 

VB .NET TCP Client Program Example - invoking the project's property page

 

 

 

 

Change the Application type: to Console Application and the Startup object: to Sub Main.

 

VB .NET TCP Client Program Example - changing the Application type: to Console Application and the Startup object: to Main() subroutine

 

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

 

VB .NET TCP Client Program Example - building the project

 

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

 

VB .NET TCP Client Program Example - running the project

 

The following is the sample output.

 

VB .NET TCP Client Program Example - a sample output in action

 

Testing the tcp client with the tcp listener. The tcp listener is a TcpListenertSampleVB program that was created previously. Firstly, we run the listener at the command prompt (in this case both client and the listener executables were copied to the C:\).

 

VB .NET TCP Client Program Example - a sample output when run from the command prompt, waiting the client connection

 

If the following Windows Security Alert box displayed, click the Unblock button.

 

VB .NET TCP Client Program Example - unblocking the Windows firewall protection

 

Then, we run the tcp client program.

 

VB .NET TCP Client Program Example - running the TCP client, connecting to the TCP listener

 

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

 

VB .NET TCP Client Program Example - the TCP listener screen when the communication with the client 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 different available options.

 


< VB .NET TcpListener & C++ .NET TCP Client Examples | Main | C++ and C# UDP Client & Server Examples >