Ejemplo n.º 1
0
        protected override async Task HandleWebSocket(WebSocketContext context, bool closeConnection = true)
        {
            if (context == null)
                throw new ApplicationException("Could not determine websocket context.");

            BlockingStream stream = new BlockingStream(16);

            var ws = context.WebSocket;

            var send = Task.Factory.StartNew(async () =>
            {
                int read = 0;
                byte[] readBuffer = new byte[1024 * 63];
                //max tcp packet size is 64K, but there is control data included, leave some bytes for that
                while ((read = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    byte[] sendBuffer = readBuffer;
                    if (read < readBuffer.Length)
                    {
                        sendBuffer = new byte[read];
                        Buffer.BlockCopy(readBuffer, 0, sendBuffer, 0, read);
                    }

                    await
                        ws.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true,
                            CancellationToken.None);
                }
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            });

            StreamHandlerAction(stream);
            stream.CompleteWriting();

            Task.WaitAll(send);
        }
Ejemplo n.º 2
0
        public void BlockingStream()
        {
            Random random = new Random();

            byte[] randomBytes = new byte[1024 * 1024];
            random.NextBytes(randomBytes);
            using (BlockingStream stream = new BlockingStream(16))
            {
                var producer = Task.Factory.StartNew(() =>
                {
                    byte[] buffer = new byte[16 * 1024];//ChunkSize
                    for (int i = 0; i < randomBytes.Length / buffer.Length; i++)
                    {
                        Buffer.BlockCopy(randomBytes, i * buffer.Length, buffer, 0, buffer.Length);
                        stream.Write(buffer, 0, buffer.Length);
                    }
                    stream.CompleteWriting();
                });

                byte[] readBuffer = new byte[3 * 1024];
                using (MemoryStream actualStream = new MemoryStream())
                {
                    int read = 0;
                    while ((read = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    {
                        actualStream.Write(readBuffer, 0, read);
                    }

                    Assert.True(randomBytes.SequenceEqual(actualStream.ToArray()));
                }

                Task.WaitAll(producer);
            }
        }