< C++ Binary Socket Client-Server Program Example | Main | C# Binary Client Socket Program Example >

 


 

Chapter 4 Part 6:

Serialization

 

 

What do we have in this chapter 4 part 6?

  1. C# Binary Socket Server Program Example

  2. Adding C# Binary Server Socket Program Example

  3. Adding C# Shared DLL Program Example

 

 

C# Binary Socket Server Program Example

 

In the following example, we create two solutions with three projects (server, shared DLL and client program). Create a new empty project. You can use the solution and project names as shown in the following Figure.

 

C# Binary Socket Server Program Example - Invoking the new project menu

 

C# Binary Socket Server Program Example - Creating a new empty project

 

Adding C# Binary Server Socket Program Example

 

Add a class named BinServerClass.

 

Adding C# Binary Server Socket Program Example - adding a new item into existing project

 

C# Binary Socket Server Program Example - adding a new class into existing project

 

C# Binary Socket Server Program Example - a new source file for the class added to the existing project

 

Adding C# Shared DLL Program Example

 

Next, add a new project.

 

C# Binary Socket Server Program Example - invoking the Add new project page

 

Select a Class Library for the Templates: and name the class as BinData.

 

C# Binary Socket Server Program Example - adding new class library project into existing project

 

Now, in this solution, we have two projects, one is the DLL (shared DLL) and another one is a console mode application (server).

 

C# Binary Socket Server Program Example - several projects in one solution

 

Next, rename the Class1 of the BinData to BinDataSubClass. Select Class1 > Right click mouse > Select Refactor > Select Rename.

 

C# Binary Socket Server Program Example - renaming the class through the context menu

 

C# Binary Socket Server Program Example - changing the class name

 

Click Apply to do the renaming.

 

C# Binary Socket Server Program Example - the preview page of the class renaming process

 

Add the following codes for the BinDataSubClass.

 

    [Serializable]

    public class BinDataSubClass

    {

        public int SubField1;

 

        /// <summary>

        /// Simple constructor for the class which initialized the properties

        /// </summary>

        public BinDataSubClass()

        {

            SubField1 = -1;

        }

 

        /// <summary>

        /// Prints the class values to the console

        /// </summary>

        public void Print()

        {

            Console.WriteLine("In BinDataSubClass...");

            Console.WriteLine("BinDataSubClass.SubField1 = {0}", SubField1);

        }

     }

 

Next, add the following class just after the previous class.

 

    [Serializable]

    public class BinDataClass

    {

        public int Field1;

        public string Field2;

        public BinDataSubClass SubClass;

 

        /// <summary>

        /// Simple constructor that initializes the member properties.

        /// </summary>

        public BinDataClass()

        {

            SubClass = new BinDataSubClass();

 

            Field1 = 1234;

            Field2 = "Field2";

        }

 

        /// <summary>

        /// Prints the class members to the console

        /// </summary>

        public void Print()

        {

            Console.WriteLine("In BinDataClass...");

            Console.WriteLine("BinDataClass.Field1 = {0}", Field1);

            Console.WriteLine("BinDataClass.Field2 = {0}", Field2);

            SubClass.Print();

        }

    }

 

Build the shared DLL.

 

C# Binary Socket Server Program Example - building the project

 

Make sure there is no error that can be seen in the VS Output window.

 

C# Binary Socket Server Program Example - output messages as seen in the Visual Studio 2008 Output window

 

If there is no error, the DLL should be generated as shown below. The DLL cannot be run individually.

 

C# Binary Socket Server Program Example - the generated DLL file

 

A complete code for this part is given below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace BinData

{

    [Serializable]

    public class BinDataSubClass

    {

        public int SubField1;

 

        /// <summary>

        /// Simple constructor for the class which initialized the properties

        /// </summary>

        public BinDataSubClass()

        {

            SubField1 = -1;

        }

 

        /// <summary>

        /// Prints the class values to the console

        /// </summary>

        public void Print()

        {

            Console.WriteLine("In BinDataSubClass...");

            Console.WriteLine("BinDataSubClass.SubField1 = {0}", SubField1);

        }

     }

 

    [Serializable]

    public class BinDataClass

    {

        public int Field1;

        public string Field2;

        public BinDataSubClass SubClass;

 

        /// <summary>

        /// Simple constructor that initializes the member properties.

        /// </summary>

        public BinDataClass()

        {

            SubClass = new BinDataSubClass();

 

            Field1 = 1234;

            Field2 = "Field2";

        }

 

        /// <summary>

        /// Prints the class members to the console

        /// </summary>

        public void Print()

        {

            Console.WriteLine("In BinDataClass...");

            Console.WriteLine("BinDataClass.Field1 = {0}", Field1);

            Console.WriteLine("BinDataClass.Field2 = {0}", Field2);

            SubClass.Print();

        }

    }

}

 

Next we will do the server programming. Add the following using directives to the BinServerClass.cs.

 

using System.Net;

using System.Net.Sockets;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using BinData;

 

C# Binary Socket Server Program Example - adding the using directives  

 

Add the usage() method.

 

static void usage()

{

            Console.WriteLine("executable_file_name [/protocol IPv4|IPv6] [/port num]");

}

 

C# Binary Socket Server Program Example - adding the usage() method

 

Next, add the Main() code.

 

       static void Main(string[] args)

        {

            int Port = 5150;

            Socket ListeningSocket = null, ClientSocket = null;

            IPEndPoint LocalEndPoint = null;

            NetworkStream NetStream;

            IFormatter formatter = new BinaryFormatter();

            BinDataClass data;

            Byte[ ] buffer = new Byte[5];

            // The following declaration will generate a warning, what a crap here...

            AddressFamily ServerAddressFamily = AddressFamily.InterNetwork;

            Environment.GetCommandLineArgs();

 

            if (args.Length != 0)

            {

                // Parse the command line

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

                {

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

                    {

                        try

                        {

                            // Create the appropriate listening socket

                            Console.WriteLine("Creating the appropriate listening socket");

                            i++;

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

                            {

                                ServerAddressFamily = AddressFamily.InterNetworkV6;

                                ListeningSocket = new Socket(

                                    AddressFamily.InterNetworkV6,

                                    SocketType.Stream,

                                    ProtocolType.Tcp

                                    );

                                LocalEndPoint = new IPEndPoint(IPAddress.IPv6Any, Port);

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

                                Console.Write("IP Address: " + IPAddress.IPv6Any + ", Port: ");

                            }

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

                            {

                                ServerAddressFamily = AddressFamily.InterNetwork;

                                ListeningSocket = new Socket(

                                    AddressFamily.InterNetwork,

                                    SocketType.Stream,

                                    ProtocolType.Tcp

                                    );

                                LocalEndPoint = new IPEndPoint(IPAddress.Any, Port);

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

                                Console.Write("IP Address: " + IPAddress.Any + ", Port: ");

                            }

                            else

                            {

                                usage();

                                return;

                            }

                        }

                        catch (System.IndexOutOfRangeException)

                        {

                            usage();

                            return;

                        }

                    }

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

                    {

                        try

                        {

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

                        }

                        catch (System.IndexOutOfRangeException)

                        {

                            usage();

                            return;

                        }

                    }

                    else

                    {

                        usage();

                        return;

                    }

                }

            }

            else

            {

                usage();

                return;

            }

 

            Console.WriteLine("Port: " + Port);

            // Bind the socket to the interface we will accept connections one

            ListeningSocket.Bind(LocalEndPoint);

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

 

            // Set the listen backlog to five

            ListeningSocket.Listen(5);

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

            Console.WriteLine("I'm listening for connection buddy...");

 

            // Wait until a client connects

            ClientSocket = ListeningSocket.Accept();

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

 

            // Create a NetworkStream for the accepted client connection

            NetStream = new NetworkStream(ClientSocket);

            Console.WriteLine("Instantiating a NetworkStream...");

 

            // Read the string "hello" from the stream since this was send before the serialized object.

            NetStream.Read(buffer, 0, 5);

 

            // Deserialize the object from the stream

            data = (BinDataClass)formatter.Deserialize(NetStream);

 

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

            data.Print();

 

            // Close up

            Console.WriteLine("Closing all...");

            ListeningSocket.Close();

            NetStream.Close();

            ClientSocket.Close();

        }

 

Select SocketBinaryServerCS folder > Right click mouse > Select Add Reference. We need to add a reference to the previous DLL in order to resolve the BinData namespace (using BinData;).

 

C# Binary Socket Server Program Example - invoking the Add Reference page

 

Click the Projects tab > Select the BinData field and click OK.

 

C# Binary Socket Server Program Example - selecting and importing the DLL file into the project

 

You can verify the added reference through the Project Dependencies as shown in the following steps.

 

C# Binary Socket Server Program Example - viewing the project dependencies

 

C# Binary Socket Server Program Example - a list of project's dependencies

 

The reference to the BinData included under the References folder.

 

C# Binary Socket Server Program Example - viewing the References in the Solution explorer

 

Next, build the project. Select SocketBinaryServerCS folder > Right click mouse > Select Build.

 

C# Binary Socket Server Program Example - building the project

 

Then, run the program. In this case we run the executable at the command prompt and we need to make sure the BinData.dll must be available to the executable. In this case we put (copy) the BinData.dll and the SocketBinaryServerCS.exe under the C:\

 

C# Binary Socket Server Program Example - a sample output

 

The following is the output sample when run at the command prompt.

 

C# Binary Socket Server Program Example - a sample output with arguments in action, waiting for connections

 

A complete code for this part is given below.

 

using System;

using System.Net;

using System.Net.Sockets;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using BinData;

 

namespace SocketBinaryServerCS

{

    class BinServerClass

    {

        static void usage()

        {

            Console.WriteLine("executable_file_name [/protocol IPv4|IPv6] [/port num]");

        }

 

        static void Main(string[ ] args)

        {

            int Port = 5150;

            Socket ListeningSocket = null, ClientSocket = null;

            IPEndPoint LocalEndPoint = null;

            NetworkStream NetStream;

            IFormatter formatter = new BinaryFormatter();

            BinDataClass data;

            Byte[ ] buffer = new Byte[5];

            // The following declaration will generate a warning, what a crap here...

            AddressFamily ServerAddressFamily = AddressFamily.InterNetwork;

 

            Environment.GetCommandLineArgs();

 

            if (args.Length != 0)

            {

                // Parse the command line

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

                {

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

                    {

                        try

                        {

                            // Create the appropriate listening socket

                            Console.WriteLine("Creating the appropriate listening socket");

                            i++;

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

                            {

                                ServerAddressFamily = AddressFamily.InterNetworkV6;

                                ListeningSocket = new Socket(

                                    AddressFamily.InterNetworkV6,

                                    SocketType.Stream,

                                    ProtocolType.Tcp

                                    );

                                LocalEndPoint = new IPEndPoint(IPAddress.IPv6Any, Port);

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

                                Console.Write("IP Address: " + IPAddress.IPv6Any + ", Port: ");

                            }

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

                            {

                                ServerAddressFamily = AddressFamily.InterNetwork;

                                ListeningSocket = new Socket(

                                    AddressFamily.InterNetwork,

                                    SocketType.Stream,

                                    ProtocolType.Tcp

                                    );

                                LocalEndPoint = new IPEndPoint(IPAddress.Any, Port);

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

                                Console.Write("IP Address: " + IPAddress.Any + ", Port: ");

                            }

                            else

                            {

                                usage();

                                return;

                            }

                        }

                        catch (System.IndexOutOfRangeException)

                        {

                            usage();

                            return;

                        }

                    }

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

                    {

                        try

                        {

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

                        }

                        catch (System.IndexOutOfRangeException)

                        {

                            usage();

                            return;

                        }

                    }

                    else

                    {

                        usage();

                        return;

                    }

                }

            }

            else

            {

                usage();

                return;

            }

 

            Console.WriteLine("Port: " + Port);

            // Bind the socket to the interface we will accept connections one

            ListeningSocket.Bind(LocalEndPoint);

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

 

            // Set the listen backlog to five

            ListeningSocket.Listen(5);

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

            Console.WriteLine("I'm listening for connection buddy...");

 

            // Wait until a client connects

            ClientSocket = ListeningSocket.Accept();

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

 

            // Create a NetworkStream for the accepted client connection

            NetStream = new NetworkStream(ClientSocket);

            Console.WriteLine("Instantiating a NetworkStream...");

 

            // Read the string "hello" from the stream since this was send before the serialized object.

            NetStream.Read(buffer, 0, 5);

 

            // Deserialize the object from the stream

            data = (BinDataClass)formatter.Deserialize(NetStream);

 

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

            data.Print();

 

            // Close up

            Console.WriteLine("Closing all...");

            ListeningSocket.Close();

            NetStream.Close();

            ClientSocket.Close();

        }

    }

}

 

 

 


 

< C++ Binary Socket Client-Server Program Example | Main | C# Binary Client Socket Program Example >