Python “talks” to C#

One of the problem that I’ve faced to when I started to do machine learning was to make Python be able to communicate with C# (or other programming languages).
Why communicate?
Because of the support from huge number of machine learning libraries that made Python the top choice for coding things in this field. In the other hand, C# .NET is the best tool to create applications from web to desktop environments. One might think about creating a machine learning software with web built by C# and connect to core machine learning in Python. In this article I’d like to propose a solution that helps Python can “talk” to C# and vice versa.
I’ve tried to search on the internet and found some tutorials to help. What I found was almost a “quick and dirty” method that creates a OS Powershell Process to execute a target .py file from C#. However, this was not what I want because I need a method that can interfere deeper in the process of the machine learning code. Moreover, I might need to get the outcome from python code which is sophisticated to do.
I finally came up with a solution: use TCP Socket. Please see the diagram below:

Basically, Python will act as a TCP server to host requests from C#. C# will be a TCP client that connects to the Python server, and that’s how communication goes.
First, we create server socket in Python:

Then, we write the code for processing the request for the server. We will make it very simple here to understand the code easily. Once understood, you can tweak the code later. For now, we only process 2 kinds of request from client: If receiving “exit” message, the server will disconnect and stop. Otherwise, it will echo back the message to the client then close the connection.

It’s the Python server. Now we move on to client side in C#.

Please read the code comments to understand the code.

Enjoy coding!:)

No Comments

Post A Comment