< C# Binary Socket Server Program Example | Main | VB .NET Binary Socket Client-Server Program Example 1>

 


 

 

Chapter 4 Part 7:

Serialization

 

 

What do we have in this chapter 4 part 7?

  1. C# Binary Client Socket Program Example - The client program.

  2. Testing the C# Client and Server Program

 

 

C# Binary Client Socket Program Example - The client program

 

In this practice we will build a client program that will use the shared DLL and communicate with the server program created previously.

Create a new empty C# project. The solution and project names are shown in the following Figure.

 

C# Binary Client Socket Program Example - The client program - creating a new empty project

 

Next, add a new class as shown in the following steps.

 

C# Binary Client Socket Program Example - The client program - adding new class to the existing project

 

Use the following class name.

 

C# Binary Client Socket Program Example - The client program - adding a new class template to the existing project

 

Add and edit the code for client as shown below.

 

// This is the client side to the socket serialization sample. This sample illustrates

// binary serialization over a socket stream. The client establishes a connection to

// the given server and serializes an instance of a BinDataClass class.

//

// Usage:

//      executable_file_name [/server server-name] [/port port-number]

//

// Sample usage:

//      executable_file_name /server myserver /port 5150

using System;

using System.Net;

using System.Net.Sockets;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using BinData;              // Common data structure to send on wire

 

namespace SocketBinaryClientCS

{

    /// <summary>

    /// This is the client side of the socket sample which serializes an instance of the

    /// BinDataClass class to the server.

    /// </summary>

    class BinClientClass

    {

        /// <summary>

        /// Displays usage information for calling the client.

        /// </summary>

        static void usage()

        {

            Console.WriteLine("usage: executable_file_name [/server server-name] [/port port-number]");

            Console.WriteLine("Else, default values will be used...");

            Console.WriteLine();

        }

 

        /// <summary>

        /// Main application that parses the command line, resolves the server's host name,

        /// establishes a socket connection, and serializes the data to the server.

        /// </summary>

        /// <param name="args">Command line arguments passed to client</param>

        static void Main(string[ ] args)

        {

            string ServerName = "localhost";

            int Port = 5150;

 

            usage();

 

            // Parse command line arguments if any. However without any argument(s) or wrong

            // argument(s), default will be used: localhost:5150. Well, this just dummy...

            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 = System.Convert.ToInt32(args[++i].ToString());

                    }

                }

                catch (System.IndexOutOfRangeException)

                {

                    usage();

                    return;

                }

            }

 

            // Attempt to resolve the server name specified

            try

            {

                Socket ClientSocket = null;

                IPHostEntry IpHost;

                IPEndPoint ServerEndPoint;

                string ServerAndPort;

 

                IpHost = Dns.GetHostEntry(ServerName);

 

                Console.WriteLine("Server name '{0}' resolved to {1} addresses",

                        ServerName,

                        IpHost.AddressList.Length

                        );

 

                // Walk the array of addresses return and attempt to connect to each

                // one. Take the first successful connection and use it.

                foreach (IPAddress addr in IpHost.AddressList)

                {

                    // Create the endpoint describing the address and port

                    ServerEndPoint = new IPEndPoint(addr, Port);

 

                    if (ServerEndPoint.AddressFamily == AddressFamily.InterNetwork)

                    {

                        ServerAndPort = "IPv4 - [" + addr.ToString() + "]:" + Port.ToString();

                    }

                    else

                    {

                        ServerAndPort = "IPv6 - [" + addr.ToString() + "]:" + Port.ToString();

                    }

 

                    Console.WriteLine("Attempting connection to {0}", ServerAndPort);

 

                    // Create a socket and attempt to connect to the endpoint

                    ClientSocket = new Socket(ServerEndPoint.AddressFamily, SocketType.Stream, 0);

 

                    try

                    {

                        ClientSocket.Connect(ServerEndPoint);

                    }

                    catch (SocketException err)

                    {

                        Console.WriteLine("Connection attempt to {0} failed: {1}",

                                ServerAndPort,

                                err.Message

                                );

                        ClientSocket.Close();

                        ClientSocket = null;

                        continue;

                    }

                    break;

                }

                // Make sure we have a valid socket connection before continuing

                if ((ClientSocket != null) && (ClientSocket.Connected == true))

                {

                    string s = "Hello";

                    Byte[ ] buf = System.Text.Encoding.ASCII.GetBytes(s.ToCharArray());

                    BinDataClass binclass;

                    NetworkStream NetStream;

                    IFormatter formatter;

 

                    binclass = new BinDataClass();

                    NetStream = new NetworkStream(ClientSocket);

                    formatter = new BinaryFormatter();

 

                    try

                    {

                        // Send some data on socket before serializing the object. The server

                        // must consume this data before deserializing the object otherwise

                        // a serialization exception will occur.

                        ClientSocket.Send(buf);

 

                        binclass.Field2 = "Client - Replaced original text with this message";

                        Console.WriteLine("Serializing the following object:");

                        binclass.Print();

                        formatter.Serialize(NetStream, binclass);

                    }

                    catch (SocketException err)

                    {

                        Console.WriteLine("A socket error occurred: " + err.Message);

                    }

                    catch (System.Runtime.Serialization.SerializationException err)

                    {

                        Console.WriteLine("A serialization error occurred: " + err.Message);

                    }

                    // Free up the resources

                    NetStream.Close();

                }

                // Close socket resource. This check needs to be outside the previous

                // control block since its possible a socket was created but the connect call failed.

                if (ClientSocket != null)

                {

                    ClientSocket.Close();

                    ClientSocket = null;

                }

            }

            catch (SocketException err)

            {

                // This will catch DNS errors. If name resolution fails we might as well

                // exit since we don't know the server's address.

                Console.WriteLine("Socket error: " + err.Message);

            }

            return;

        }

    }

}

 

Next, add a reference to the BinData DLL. The steps are shown below.

 

C# Binary Client Socket Program Example - The client program - invoking the Add Reference page through menu  

 

C# Binary Client Socket Program Example - The client program - selecting the DLL file

 

The reference can be seen under the References folder.

 

C# Binary Client Socket Program Example - The client program - the included DLL file as seen through Solution Browser under the project folder

 

Next, build the program.

 

C# Binary Client Socket Program Example - The client program - building the project

 

And then, run the program.

 

C# Binary Client Socket Program Example - The client program - runnng the project without debugging

 

C# Binary Client Socket Program Example - The client program - the output sample using default argument values

 

Testing the C# Client and Server Program

 

Running both the client and the server programs. To see the real communication between the server and the client programs we need to run both programs. In this case we copy all the executables (SocketBinaryServerCS.exe and SocketBinaryClientCS.exe) and DLL (BinData.dll) files and put them under the C:\. Firstly, run the server followed by the client.

 

Run the server program and it starts listening for connection.

 

Testing the C# Client and Server Program - running the server program with argument values, waiting for connections

 

Run the client in another console, serializing the objects.

 

Testing the C# Client and Server Program - running the client program connecting to the server program

 

And then the server responses, de-serializing the objects.

 

Testing the C# Client and Server Program - the server program when the communication was completed

 

 

 


 

< C# Binary Socket Server Program Example | Main | VB .NET Binary Socket Client-Server Program Example 1>