How to resolve the algorithm Distributed programming step by step in the C# programming language
How to resolve the algorithm Distributed programming step by step in the C# programming language
Table of Contents
Problem Statement
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language. This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Distributed programming step by step in the C# programming language
This code demonstrates distributed programming using TCP sockets in C#. It includes both a client and a server implementation. Let's break down the code step by step:
-
Classes and Methods:
- The
DistributedProgramming
class contains twoasync
methods:RunClient
andRunServer
. These methods will be used to start the client and server respectively. - The
SampleData
class is a simple data transfer object (DTO) that represents the data being sent between the client and server.
- The
-
Constants:
const int Port = 555;
: This is the port number used for communication.
-
RunClient
Method:- This method represents the client side.
- It starts by connecting to the server at
localhost
(the local computer) on port555
. - Next, it serializes (converts to a byte array) an instance of
SampleData
usingSerialize
and sends it to the server usingawait stream.WriteAsync
. - Finally, it receives a response from the server (a string containing 'Thanks!') using
await stream.ReadAsync
and deserializes it usingDeserialize
.
-
RunServer
Method:- This method represents the server side.
- It starts by creating a TCP listener on port
555
. - It waits for a client to connect using
await listener.AcceptTcpClientAsync
. - When a client connects, it receives the incoming data using
await stream.ReadAsync
and deserializes it into an instance ofSampleData
. - It then sends a response ('Thanks!') to the client using
await stream.WriteAsync
after serializing it.
-
Serialization:
Serialize
andDeserialize
methods are used to convert objects into byte arrays and back.BinaryFormatter
class is used for binary serialization and deserialization.
-
Main Method:
- The
Main
method is the entry point of the program. - It expects a single command-line argument ("client" or "server") specifying the role the program should play.
- Based on the argument, it calls either
RunClient
orRunServer
to start the appropriate functionality.
- The
When the program runs with the "client" argument, it starts a client that connects to the server and sends a SampleData
object representing some loot with a specific latitude and longitude. The server responds with a "Thanks!" message to acknowledge receipt of the loot.
When the program runs with the "server" argument, it starts a server that listens for incoming client connections. When a client connects, the server receives the loot data, acknowledges it with a "Thanks!" message, and prints out the loot information.
In summary, this code demonstrates a simple client-server communication using TCP sockets, where the client sends loot information to the server, and the server responds with a thank-you message.
Source code in the csharp programming language
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
You may also check:How to resolve the algorithm Check output device is a terminal step by step in the OCaml programming language
You may also check:How to resolve the algorithm Fraction reduction step by step in the Python programming language
You may also check:How to resolve the algorithm Test a function step by step in the Tcl programming language
You may also check:How to resolve the algorithm Assertions step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Self-describing numbers step by step in the Seed7 programming language