Пример #1
0
    public static async Task <Connection> CreateAsync()
    {
        var conn = new Connection("9090", new StreamSocketListener());

        conn.SocketListener.Control.KeepAlive   = false;
        conn.SocketListener.ConnectionReceived += async(sender, args) =>
        {
            Debug.Log("Connection received");
            // get rid of old MessageQueue, which has completed
            // var oldMessageQueue = Interlocked.Exchange(ref conn.MessageQueue, new BufferBlock<MessageComposer.Payload>(BlockOptions));
            try
            {
                while (true)
                {
                    // get latest frames
                    Tuple <MessageComposer.Payload, MessageComposer.Payload> frames = null;
                    while (frames == null)
                    {
                        Debug.Log("Waiting for frames");
                        // until we have a pair of frames
                        frames = await conn.GetFrames();
                    }
                    // compose and send a chunked message
                    using (var dw = new DataWriter(args.Socket.OutputStream))
                    {
                        Debug.Log("Writing msg");
                        dw.WriteBytes(MessageComposer.GetMessage(frames.Item1)); // depth
                        await dw.StoreAsync();

                        dw.WriteBytes(MessageComposer.GetMessage(frames.Item2)); // color
                        await dw.StoreAsync();

                        // flush
                        await dw.FlushAsync();

                        dw.DetachStream();
                        Debug.Log("Done");
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log($"Connection terminated: {e.Message}");
            }
            finally
            {
                await conn.ClearFrames();
            }
        };
        Debug.Log($"OutboundSocket listening on port {conn.Port}");
        // may throw if port is unavailable
        await conn.SocketListener.BindServiceNameAsync(conn.Port);

        return(conn);
    }