【问题标题】:Named Pipes IPC: Python server, C# Client命名管道 IPC:Python 服务器、C# 客户端
【发布时间】:2019-07-16 11:51:23
【问题描述】:

标题总结了它。有很多关于 c# 服务器和 python 客户端来回通信的示例。

我想了解如何改为创建 python 服务器和 c# 客户端以进行一些进程间通信。

【问题讨论】:

  • 如果你有相反的例子,你不能只翻译代码吗?
  • 获取任何在 Python 中设置命名管道服务器的东西(例如来自 this question)并从那里开始。查找 C# 的客户端代码将不是问题。

标签: c# python-3.x ipc


【解决方案1】:

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

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

我发现 dotnet core 的另一个挫折是,在创建套接字或连接到一个套接字时,NamedPipeServerStreamNamedPipeClientStream 类将在开头添加“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多