Inter Process Communication in .net and Framework

Recently I was working on a .net Framework 4.8 application and there was one feature which I wanted to implement. But this feature has support only in the .net core 3.0 onwards.

To resolve this issue I decided to take an approach of inter process communication through TCP Listener and Client

Here is the code snippet for TCPListener written in .net 8

static async Task Main(string[] args)
{
    var listener = new TcpListener(IPAddress.Any, 12346);
    listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    listener.Start();
    Console.WriteLine("Server started and listening on port 12346...");

    while (true)
    {
        var client = await listener.AcceptTcpClientAsync();
        Console.WriteLine("Client connected...");
        _ = HandleClientAsync(client);
    }
}

In the above code, I have initialized the TcpListener object to listen the incoming message on any IP address on the port number 12346.

Then I wanted the listener to entertain all type of the sockets and to reuse the addresses.
Reuse address is used because the Listener and Client are running on the same machine.

Once all these options are set, listener is to be started.
Now we have to invoke the AcceptTcpClientAsync method on the listener so that it can accept the communication request from the TcpClient.

Once the connection is established, we have to handle the TcpClient’s request.
It has been handled in the HandleClientAsync method.

Here goes the code for handler.

private static async Task HandleClientAsync(TcpClient client)
{
    try
    {
        using var networkStream = client.GetStream();
        var buffer = new byte[4096];
        int bytesRead = await networkStream.ReadAsync(buffer, 0, buffer.Length);
        string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine($"Received message: {receivedMessage}");

        var response = string.Empty;
        //Specific logic for handling the receivedMessage goes here
        
        byte[] responseBytes = Encoding.UTF8.GetBytes(response);
        await networkStream.WriteAsync(responseBytes, 0, responseBytes.Length);
        Console.WriteLine("Response sent to client.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
    }
    finally
    {
        client.Close();
        Console.WriteLine("Client disconnected.");
    }
}

Along with TcpClient a NetworkStream is attached on which it writes data and read from it.
So in the above code, one has to get the stream from TcpClient and then has to read the data in a byte array.
Once data is read, it can be processed as required.
To send back the data to client, it is to be written on the same network stream.
TcpClient will read the data from this stream.

Here goes the code for client

static void Main(string[] args)
{
    string message = "ENCRYPT:Your data to encrypt";
    string response = SendMessage("127.0.0.1", 12346, message);
    Console.WriteLine("Response from server: " + response);
}

static string SendMessage(string server, int port, string message)
{
	try
	{
		using (var client = new TcpClient(server, port))
		{
			using (var stream = client.GetStream())
			{
				byte[] data = Encoding.UTF8.GetBytes(message);
				stream.Write(data, 0, data.Length);

				byte[] responseData = new byte[4096];
				int bytes = stream.Read(responseData, 0, responseData.Length);
				return Encoding.UTF8.GetString(responseData, 0, bytes);
			}
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine($"Exception: {ex.Message}");
		return string.Empty;
	}
}

Communication Process

 

  • Server Initialization:The server starts listening on the loopback address and specified port.
  • Client Connection:The client initiates a connection to the server’s loopback address and port.
  • Message Sending:The client sends a message (e.g., “ENCRYPT:Your data to encrypt”. In my case the required encryption was not available in .net framework natively) to the server over the established TCP connection.
  • Server Processing:The server receives the message, processes it (encryption or decryption), and prepares a response.
  • Response Sending:The server sends the processed response back to the client over the same TCP connection.
  • Client Receiving:The client reads the server’s response and displays it.

 

By following this setup, the server will only accept connections from clients running on the same machine, ensuring local-only communication.

That’s all for now. Enjoy the coding.

About sagar

With over 13 years of professional experience as a .NET developer, I have honed my expertise in various facets of the .NET framework and related technologies. My extensive background includes proficiency in WPF, Web APIs, WCF services, and Windows services, which has enabled me to deliver robust and scalable applications across different domains.

Leave a Reply

Your email address will not be published. Required fields are marked *