使用Reactive Extensions(Rx)实现套接字编程?

时间:2010-06-25 13:18:54

标签: c# .net sockets system.reactive

使用Rx编写GetMessages函数的最简洁方法是什么:

static void Main()
{
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    var messages = GetMessages(socket, IPAddress.Loopback, 4000);
    messages.Subscribe(x => Console.WriteLine(x));

    Console.ReadKey();
}

static IObservable<string> GetMessages(Socket socket, IPAddress addr, int port)
{
    var whenConnect = Observable.FromAsyncPattern<IPAddress, int>(socket.BeginConnect, socket.EndConnect)(addr, port);

    // now will receive a stream of messages
    // each message is prefixed with an 4 bytes/Int32 indicating it's length. 
    // the rest of the message is a string

    // ????????????? Now What ????????????? 
}

一个简单的服务器作为上述示例的驱动程序:http://gist.github.com/452893#file_program.cs

使用Rx进行套接字编程

我一直在研究使用Reactive Extensions进行一些套接字编程工作。我这样做的动机是它会以某种方式使代码“更简单”。这是否意味着更少的代码,更少的嵌套在这些线上。

然而到目前为止似乎并非如此:

  1. 我没有找到很多使用Rx和套接字的例子
  2. 我发现的example s 看起来并不像现有的BeginXXXX,EndXXXX代码那么复杂
  3. 虽然Observable具有FromAsyncPattern的扩展方法,但这不包括SocketEventArgs异步API。
  4. 当前的非工作解决方案

    这是我到目前为止所拥有的。这不起作用,它因堆栈溢出而失败(呵呵)我没有弄清楚语义,所以我可以创建一个IObservable来读取指定数量的字节。

        static IObservable<int> GetMessages(Socket socket, IPAddress addr, int port)
        {
            var whenConnect = Observable.FromAsyncPattern<IPAddress, int>(socket.BeginConnect, socket.EndConnect)(addr, port);
    
            // keep reading until we get the first 4 bytes
            byte[] buffer = new byte[1024];
            var readAsync = Observable.FromAsyncPattern<byte[], int, int, SocketFlags, int>(socket.BeginReceive, socket.EndReceive);
    
            IObservable<int> readBytes = null;
            var temp = from totalRead in Observable.Defer(() => readBytes)
                       where totalRead < 4
                       select readAsync(buffer, totalRead, totalRead - 4, SocketFlags.None);
            readBytes = temp.SelectMany(x => x).Sum();
    
            var nowDoSomethingElse = readBytes.SkipUntil(whenConnect);
        }
    

2 个答案:

答案 0 :(得分:8)

这些方面的某些方面可行。这未经过测试,未考虑异常以及部分返回消息的情况。但除此之外,我相信这是一个正确的方向。

    public static IObservable<T> GetSocketData<T>(this Socket socket,
        int sizeToRead, Func<byte[], T> valueExtractor)
    {
        return Observable.CreateWithDisposable<T>(observer =>
        {
            var readSize = Observable
                .FromAsyncPattern<byte[], int, int, SocketFlags, int>(
                socket.BeginReceive,
                socket.EndReceive);
            var buffer = new byte[sizeToRead];
            return readSize(buffer, 0, sizeToRead, SocketFlags.None)
                .Subscribe(
                x => observer.OnNext(valueExtractor(buffer)),
                    observer.OnError,
                    observer.OnCompleted);
        });
    }

    public static IObservable<int> GetMessageSize(this Socket socket)
    {
        return socket.GetSocketData(4, buf => BitConverter.ToInt32(buf, 0));
    }

    public static IObservable<string> GetMessageBody(this Socket socket,
        int messageSize)
    {
        return socket.GetSocketData(messageSize, buf =>
            Encoding.UTF8.GetString(buf, 0, messageSize));
    }

    public static IObservable<string> GetMessage(this Socket socket)
    {

        return
            from size in socket.GetMessageSize()
            from message in Observable.If(() => size != 0,
                socket.GetMessageBody(size),
                Observable.Return<string>(null))
            select message;
    }

    public static IObservable<string> GetMessagesFromConnected(
        this Socket socket)
    {
        return socket
            .GetMessage()
            .Repeat()
            .TakeWhile(msg => !string.IsNullOrEmpty(msg));
    }

    public static IObservable<string> GetMessages(this Socket socket,
        IPAddress addr, int port)
    {
        return Observable.Defer(() => 
        {
            var whenConnect = Observable
                .FromAsyncPattern<IPAddress, int>(
                    socket.BeginConnect, socket.EndConnect);
            return from _ in whenConnect(addr, port)
                   from msg in socket.GetMessagesFromConnected()
                       .Finally(socket.Close)
                   select msg;
        });
    }

编辑:为了处理不完整的读取,可以使用Obaveable.While(在GetSockedData中),由Dave Sexton在same thread on RX forum中提出。

编辑:另外,请看看Jeffrey Van Gogh的文章:Asynchronous System.IO.Stream reading

答案 1 :(得分:2)

好的,所以这可能是“作弊”,但我想你可以重新定位我的非Rx答案并用Observable.Create包裹它。

我很确定返回套接字IDisposable是错误的语义,但不确定会是什么。

    static IObservable<string> GetMessages(Socket socket, IPAddress addr, int port)
    {
        return Observable.CreateWithDisposable<string>(
            o =>
            {
                byte[] buffer = new byte[1024];

                Action<int, Action<int>> readIntoBuffer = (length, callback) =>
                {
                    var totalRead = 0;

                    AsyncCallback receiveCallback = null;
                    AsyncCallback temp = r =>
                    {
                        var read = socket.EndReceive(r);

                        if (read == 0)
                        {
                            socket.Close();
                            o.OnCompleted();
                            return;
                        }

                        totalRead += read;

                        if (totalRead < length)
                        {
                            socket.BeginReceive(buffer, totalRead, length - totalRead, SocketFlags.None, receiveCallback, null);
                        }
                        else
                        {
                            callback(length);
                        }
                    };
                    receiveCallback = temp;

                    socket.BeginReceive(buffer, totalRead, length, SocketFlags.None, receiveCallback, null);
                };

                Action<int> sizeRead = null;

                Action<int> messageRead = x =>
                {
                    var message = Encoding.UTF8.GetString(buffer, 0, x);
                    o.OnNext(message);
                    readIntoBuffer(4, sizeRead);
                };

                Action<int> temp2 = x =>
                {
                    var size = BitConverter.ToInt32(buffer, 0);
                    readIntoBuffer(size, messageRead);
                };
                sizeRead = temp2;

                AsyncCallback connectCallback = r =>
                {
                    socket.EndConnect(r);
                    readIntoBuffer(4, sizeRead);
                };

                socket.BeginConnect(addr, port, connectCallback, null);

                return socket;
            });
    }