Click here to Skip to main content
15,917,862 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing message communication through c# and pipe using PIPE


I am able send message through c# and received in python but python not able to send back to c#

i out output should be like this

C# side screen:                            

Server :
print('hello')
Data Sent :print('hello')

In python side data  be display 

hello

Now i want to received same data to my c# side 
expected will be 

C#:
print('hello')
Data Sent :print('hello')
Data Received :hello



I am using ReceivedFromPython() method to received data from python
Please Can review code where i am doing mistake 
Looking forward response from you soon

What I have tried:

My c# code 

<pre>  public class OpenPipe
    {

        private readonly NamedPipeClientStream _pipeClient;
        public OpenPipe(string serverId)
        {
            _pipeClient = new NamedPipeClientStream(".", serverId, PipeDirection.InOut);
        }

        StreamWriter sw;
        StreamReader sr;
        public void Start()
        {
            // const int tryConnectTimeout = 5 * 60 * 1000; // 5 minutes
            //const int tryConnectTimeout = 5 * 60 * 1000;  //1sec;
            _pipeClient.Connect();

            sw = new StreamWriter(_pipeClient);
            sr = new StreamReader(_pipeClient);
            sw.AutoFlush = true;

        }

        public void Stop()
        {
            try
            {
                _pipeClient.WaitForPipeDrain();
            }
            finally
            {
                sw.Close(); 
                sr.Close();
                _pipeClient.Close();
                _pipeClient.Dispose();

            }

        }
        public string SendToPython(string data)
        {

            //using (StreamWriter sw = new StreamWriter(_pipeClient))
            {
                try
                {
                    //var data1 = string.Empty;
                    //while (!data.Equals("quit", StringComparison.InvariantCultureIgnoreCase))
                    {
                        _pipeClient.WaitForPipeDrain();

                        sw.WriteLine(data);
                        
                    }
                    return data;
                }
                catch (Exception exc)
                {

                    return exc.Message;
                }

            }
        }

        public string ReceivedFromPython()
        {

            string resp = "";
            //Start();
            //using (StreamReader reader = new StreamReader(_pipeClient))
            {
                //var data = string.Empty;
                //while ((data = sr.ReadLine()) != null)
                {
                    while (!sr.EndOfStream)
                        resp += sr.ReadLine();
                    // Console.WriteLine("CLIENT:" + resp);
                }
                //Console.Write("[CLIENT] Press Enter to continue...");
                //Console.ReadLine();
            }
            return resp;

        }

    }
}


Main programs.cs
static void Main(string[] args)
       {
           //var respData;
           OpenPipe client = new OpenPipe("CSServer");
           client.Start();
           //var command1topython = "a = 5; print(\"Expected a = 4. Actual a = {} \".format(vara))";
           //var commandToPython = " Hello from C#";
           string data = "";
           //while (!data.Equals("quit", StringComparison.InvariantCultureIgnoreCase))
           while(true)
           {
               Console.WriteLine("Server : ");
               data = Console.ReadLine();



               if (data.Equals("quit", StringComparison.InvariantCultureIgnoreCase))
                  break;

               string data_Sent = client.SendToPython(data);
               Console.WriteLine("Data Sent :" + data_Sent);

               System.Threading.Thread.Sleep(1000);

               string resp = client.ReceivedFromPython();
               Console.WriteLine("Data Received :" + resp);
           }

             client.Stop();



}


python code main.py


from base64 import b16decode
from cgitb import text
from doctest import OutputChecker
from importlib.resources import Path, path
import time
import sys,os
import subprocess,shlex
from pathlib import Path
from tkinter import Text
import win32pipe, win32file, pywintypes
from demo import *
from subprocess import Popen,PIPE, TimeoutExpired



def PipeClient():
    print("pipe client")
    quit = False

    while not quit:
        try:
            pipeName="CSServer"
            pipe_handle = win32pipe.CreateNamedPipe(
              r'\\.\pipe\\'+pipeName,
            win32pipe.PIPE_ACCESS_DUPLEX,
            win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
            1, 65536, 65536,
            0,
            None)
            win32pipe.ConnectNamedPipe(pipe_handle, None)
            
            res = win32pipe.SetNamedPipeHandleState(pipe_handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)
            if res == 0:
                print(f"SetNamedPipeHandleState return code: {res}")
            while True:
                # Receive data from C# client
                (_, read_message) = win32file.ReadFile(pipe_handle, 1000)
                #print(read_message)
                
                
                stdoutOrigin=sys.stdout 
                sys.stdout = open("log.txt", "w")
                exec(read_message)
                sys.stdout=stdoutOrigin
                with open('log.txt',encoding="utf-8") as f:
                    result =  f.read()
                    print(result)
                    #win32file.WriteFile(pipe_handle, result.encode()+ b'\n')
                    win32file.WriteFile(pipe_handle, result.encode())
                f.close()  
            
              

            
        
        except pywintypes.error as e:
            if e.args[0] == 2:
                print("no pipe, trying again in a sec")
                time.sleep(1)
            elif e.args[0] == 109:
                print("broken pipe, bye bye")
                quit = True


t = PipeClient()
Posted
Updated 25-Aug-22 2:34am
v3
Comments
Dave Kreskowiak 25-Aug-22 9:59am    
DO NOT go back and replace your original question with a "thank you!" If you do that, the answers below no longer make any sense.

1 solution

I have a working version from your original question on this subject which you can use to build on:
1. The C# console application
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.IO.Pipes;

class Test
{
    static int CsTest()
    {
        int rc = 0;

        using (NamedPipeClientStream pipeClient =
           new NamedPipeClientStream(".", "CSServer", PipeDirection.InOut))
        {
            // Connect to the pipe or wait until the pipe is available.
            Console.Write("Attempting to connect to pipe...");
            pipeClient.Connect();

            Console.WriteLine("Connected to pipe.");
            Console.WriteLine("There are currently {0} pipe server instances open.",
                pipeClient.NumberOfServerInstances);
            StreamWriter sw = new StreamWriter(pipeClient);
            StreamReader sr = new StreamReader(pipeClient);
            while (true)
            {
                try
                {
                    sw.AutoFlush = true;
                    sw.WriteLine("Hello from c#");
                    //  Console.WriteLine("Received: " + temp);
                    string temp = sr.ReadLine();
                    Console.WriteLine("Received from python : {0}", temp);
                    // Console.ReadLine();
                }
                catch (EndOfStreamException)
                {
                    break;                    // When client disconnects
                }
            }

        }

        return rc;
    }

    static void Main(string[] args)
    {
        int result = CsTest();
        Console.WriteLine($"\nC# test result: {result}");
    }
}

2. The Python application
Python
import win32file
import win32pipe
import time

# Python 2 pipe server (ReadThenWrite)
pipeName="CSServer"
pipe_handle = win32pipe.CreateNamedPipe(
        r'\\.\pipe\\'+pipeName,
        win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536,
        0,
        None)
win32pipe.ConnectNamedPipe(pipe_handle, None)
while True:
    
    ret, read_message = win32file.ReadFile(pipe_handle, 1000)
    print(F'{ret = } Received from c#: ' + read_message.decode('utf-8'))

    ret, length = win32file.WriteFile(pipe_handle, 'Hello from Python\n'.encode())
    print(F'{ret = }, {length = } from WriteFile')

    win32file.FlushFileBuffers(pipe_handle)
   # win32pipe.DisconnectNamedPipe(pipe_handle)
    #win32file.CloseHandle(pipe_handle)

    time.sleep(2)

You can use this to test the basic connection between the two sides, and then add whetever other features you need.
 
Share this answer
 
Comments
HelpMewithCode 25-Aug-22 8:21am    
Yeh Thank you
CPallini 25-Aug-22 8:36am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900