|
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.
|
Add a class named BinServerClass.
Next, add a new project.
Select a Class Library for the Templates: and name the class as BinData.
Now, in this solution, we have two projects, one is the DLL (shared DLL) and another one is a console mode application (server).
Next, rename the Class1 of the BinData to BinDataSubClass. Select Class1 > Right click mouse > Select Refactor > Select Rename.
Click Apply to do the renaming.
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.
Make sure there is no error that can be seen in the VS Output window.
If there is no error, the DLL should be generated as shown below. The DLL cannot be run individually.
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; |
![]() |
|
Add the usage() method.
static void usage() { Console.WriteLine("executable_file_name [/protocol IPv4|IPv6] [/port num]"); } |
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;).
Click the Projects tab > Select the BinData field and click OK.
You can verify the added reference through the Project Dependencies as shown in the following steps.
The reference to the BinData included under the References folder.
Next, build the project. Select SocketBinaryServerCS folder > Right click mouse > Select Build.
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:\
The following is the output sample when run at the command prompt.
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(); } } } |