命名管道IPC:Python服务器,C#客户端

时间:2019-07-16 11:51:23

标签: c# python-3.x ipc

标题汇总。关于c#服务器和python客户端来回通信的大量示例。

我想了解如何改用python服务器和c#客户端进行进程间通信。

1 个答案:

答案 0 :(得分:0)

我设法找到了解决方案。首先,我首先想澄清点网核心中使用的一些令人困惑的术语和晦涩的命名约定。

NamedPipeServerStream NamedPipeClientStream 似乎实际上不在命名管道上运行,而是在Unix域套接字上运行。这意味着我们必须使用套接字在进程之间进行通信,而不是使用FIFO文件。

我对dotnet核心的另一个不满是,当创建套接字或连接到套接字时, NamedPipeServerStream NamedPipeClientStream 类会将“ CoreFxPipe_”添加到套接字的开头。套接字名称。参见related question

Python服务器

#!/usr/bin/python3

import socket
import os
import struct

SOCK_PATH = "/tmp/CoreFxPipe_mySocket"

with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
    try:
        os.remove(SOCK_PATH)
    except OSError:
        pass
    sock.bind(SOCK_PATH)
    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#客户端

using System;
using System.IO;
using System.IO.Pipes;
using System.Text;

class PipeClient
{
    static void 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...");
    }
}

来源:

https://abgoswam.wordpress.com/2017/07/13/named-pipes-c-python-net-core/

https://realpython.com/python-sockets/

https://unix.stackexchange.com/questions/75904/are-fifo-pipe-unix-domain-socket-the-same-thing-in-linux-kernel