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.
Next, add a new class as shown in the following steps. |
Use the following class name.
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.
![]() |
|
The reference can be seen under the References folder.
Next, build the program.
And then, run the program.
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.
Run the client in another console, serializing the objects.
And then the server responses, de-serializing the objects.