【问题标题】:How to use UnixDomainSocketEndPoint to create a unix socket in dotnet?如何使用 UnixDomainSocketEndPoint 在 dotnet 中创建 unix 套接字?
【发布时间】:2020-10-19 21:54:37
【问题描述】:

我有一个用 C 编写的程序,它需要将数据发送到另一个用 C# 编写的应用程序。

谁能展示一个基本的 hello world 示例,说明如何在 linux 上使用 UnixDomainSocketEndPoint。我希望 C# 应用程序成为服务器。换句话说,C 应用程序将向 C# 应用程序发送数据。 如何创建一个将监听 dotnet 上的数据的 unix 套接字(应用程序不需要回复任何内容)?


在互联网上研究时,我发现的所有东西都与单声道有关,例如这个问题: How to connect to a Unix Domain Socket in .NET Core in C# 。我试过那个例子,但它没有用。而且它没有使用 UnixDomainSocketEndPoint。

我还发现这个教程https://medium.com/@goelhardik/http-connection-to-unix-socket-from-dotnet-core-in-c-21d19ef08f8a 使用了相同的代码。

【问题讨论】:

    标签: c# c .net-core ipc unix-socket


    【解决方案1】:

    也许网上没有那么多例子,因为它比我想象的要简单。我能够在没有在互联网上进行研究的情况下回答这个问题。我应该在问之前尝试过。无论如何,这是答案:

    using System;
    using System.Net.Sockets;
    using System.Threading.Tasks;
    
    class Program
    {
        static void Main(string[] args)
        {
            var path = "/tmp/foo.sock";
    
            // client
            Task.Run(async () =>
            {
                // wait 2 seconds
                await Task.Delay(2000);
    
                using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    socket.Connect(new UnixDomainSocketEndPoint(path));
    
                    // send hello world
                    var dataToSend = System.Text.Encoding.UTF8.GetBytes("Hello-world!");
    
                    socket.Send(dataToSend);
                }
            });
    
            // Server
            {
                // delete file if it exists
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
    
                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                socket.Bind(new UnixDomainSocketEndPoint(path));
                socket.Listen(5);
                Console.WriteLine("Server started waiting for client to connect...");
    
                var s = socket.Accept();
    
                Console.WriteLine("Client connected");
    
                var buffer = new byte[1024];
                var numberOfBytesReceived = s.Receive(buffer, 0, buffer.Length, SocketFlags.None);
    
                var message = System.Text.Encoding.UTF8.GetString(buffer, 0, numberOfBytesReceived);
    
                Console.WriteLine($"Received: {message}");
            }
    
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2022-11-12
    • 2019-02-01
    • 1970-01-01
    • 2010-09-07
    • 2022-10-29
    • 2021-08-24
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多