Python Forum
Duplex Named Pipe with Python Server and C# Clients
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Duplex Named Pipe with Python Server and C# Clients
#1
Hi,

I am trying to set up a Python server to process objects from C# (.NET) clients
with a duplex named pipe. I've seen some good examples for setting up pipes,
but it's going the other way: With the server in C# and Python as the client.
Instead of "NamedPipeServerStream", I need to use "NamedPipeClientStream"
in .NET.

I came across the following code on SO:
https://stackoverflow.com/questions/5705...ect=1&lq=1

The code as downloaded has problems.

sock.bind(SOCK_PATH)
:> TypeError: bind(): AF_INET address must be tuple, not str


My immediate problem is to figure out what sock.bind wants in the way of a tuple.
I thought that giving it a port number might be what it wants, but that is wrong:
sock.bind((SOCK_PATH, 443))
#socket.gaierror: [Errno 11001] getaddrinfo failed

Can anyone please help me figure this out?

If anyone knows of a good working example on how to open a named pipe
in Python, then have clients in C# send objects through the pipe then
receive the modified object I would very much appreciate it if you'd
clue me in.

THANKS!

Here is the code:

#!/usr/bin/python3

import socket
import os
import struct

#SOCK_PATH = "/tmp/CoreFxPipe_mySocket"
#  TRY changing this to the same within C#
# 
SOCK_PATH = "/mySocket"
#  SOCK_PATH = r'\\.\pipe\mySocket'

# with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
# Change socket.AF_UNIX to socket.AF_INET for Windows
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    try:
        os.remove(SOCK_PATH)
    except OSError:
        pass
    #sock.bind(SOCK_PATH)
    #Traceback (most recent call last):
    #sock.bind(SOCK_PATH)
    #TypeError: bind(): AF_INET address must be tuple, not str

    sock.bind((SOCK_PATH, 443))
    #socket.gaierror: [Errno 11001] getaddrinfo failed

    sock.listen()
    conn, addr = sock.accept()
    with conn:
        try:
            while True:
                amount_expected = struct.unpack('I', conn.recv(4))[0]
                print("amount_expected :", amount_expected)

                message = conn.recv(amount_expected)
                print("Received message : ", message.decode())

                # Send data
                message_rev = message[::-1].decode()
                print("Sent message (reversed) : ", message_rev)

                conn.sendall(
                    struct.pack(
                        'I',
                        len(message_rev)
                    )
                    + message_rev.encode('utf-8')
                )

        except (struct.error, KeyboardInterrupt) as e:
            print(e)

        finally:
            print('closing socket')
C# Client

    class PipeClient
    {
        public void PipeClient_Main(string[] args)
        {
            using (NamedPipeClientStream
                   pipeClient = new NamedPipeClientStream
                                      (".", "mySocket", PipeDirection.InOut))
            {
    
                // Connect to the pipe or wait until the pipe is available.
                Console.WriteLine("Attempting to connect to pipe...");
                pipeClient.Connect();
    
                try
                {
                    // Read user input and send that to the client process.
                    using (BinaryWriter _bw = new BinaryWriter(pipeClient))
                    using (BinaryReader _br = new BinaryReader(pipeClient))
                    {
                        while (true)
                        {
                            //sw.AutoFlush = true;
                            Console.Write("Enter text: ");
                            var str = Console.ReadLine();
    
                            var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array
                            _bw.Write((uint)buf.Length);                // Write string length
                            _bw.Write(buf);                              // Write string
                            Console.WriteLine("Wrote: \"{0}\"", str);
                            Console.WriteLine("Let's hear from the server now..");
    
                            var len = _br.ReadUInt32();
                            var temp = new string(_br.ReadChars((int)len));
    
                            Console.WriteLine("Received from client: {0}", temp);
                        }
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
    
            }
            Console.Write("Press Enter to continue...");
        }
    }
Reply
#2
As you noticed in the S.O. example they are using socket.AF_UNIX socket type and not socket.AF_INET. That's why you have the error.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,407 Nov-09-2023, 10:56 AM
Last Post: mg24
  Resolving ImportError: No module named gdb (Python in C++) mandaxyz 3 1,400 Oct-04-2023, 02:43 PM
Last Post: mandaxyz
  Convert Excel file into csv with Pipe symbol.. mg24 4 1,308 Oct-18-2022, 02:59 PM
Last Post: Larz60+
  Check if clients are online with ips stored in json [SOLVED] AlphaInc 6 2,449 Jun-27-2022, 08:28 AM
Last Post: AlphaInc
  Stream via socket with multiple clients principemestizo 0 1,467 Nov-01-2021, 06:25 PM
Last Post: principemestizo
  How to take the tar backup files form remote server to local server sivareddy 0 1,891 Jul-14-2021, 01:32 PM
Last Post: sivareddy
  BrokenPipeError: [Errno 32] Broken pipe throwaway34 6 9,173 May-06-2021, 05:39 AM
Last Post: throwaway34
  Duplex pipes GrahamL 0 1,750 Dec-16-2020, 09:44 AM
Last Post: GrahamL
  2 or more processes on the write end of the same pipe Skaperen 4 3,835 Sep-27-2020, 06:41 PM
Last Post: Skaperen
  STT: recognition connection failed: [Errno 32] Broken pipe GrahamBerends 0 5,028 Jul-18-2020, 11:00 PM
Last Post: GrahamBerends

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020