public void Send(System.ArraySegment <byte> byteSeg)
    {
#if TEST
        bytesSend += byteSeg.Count;
#endif
        client.Send(byteSeg.Array, byteSeg.Offset, byteSeg.Count);
    }
Exemple #2
0
    public async static Task <string> Receive()
    {
        byte[] buffer  = new byte[65536];
        var    segment = new System.ArraySegment <byte>(buffer, 0, buffer.Length);
        WebSocketReceiveResult receiveResult;

        using (var cts = new CancellationTokenSource()) {
            receiveResult = await webSocket.ReceiveAsync(segment, cts.Token);

            return(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
        }
    }
Exemple #3
0
 private async System.Threading.Tasks.Task Send(string msg, int timeout)
 {
     try
     {
         using (var cts = new System.Threading.CancellationTokenSource(timeout))
         {
             var segment = new System.ArraySegment <byte>(System.Text.Encoding.UTF8.GetBytes(msg));
             await ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, cts.Token);
         }
     }
     catch (System.Threading.Tasks.TaskCanceledException)
     {
         throw new TimeoutException("Timeout when sending message.");
     }
 }
    public void Send(System.ArraySegment <byte> bytes)
    {
        if (!Connected)
        {
            return;
        }
        var stream = client.GetStream();
        int len    = bytes.Count;

        stream.WriteByte((byte)(len & 0xFF));
        stream.WriteByte((byte)(len >> 8 & 0xFF));
        stream.WriteByte((byte)(len >> 16 & 0xFF));
        stream.WriteByte((byte)(len >> 24 & 0xFF));
        stream.Write(bytes.Array, bytes.Offset, len);
        stream.Flush();
    }
Exemple #5
0
    public async Task WebSocketTinyReceiveGeneratesEndOfMessage()
    {
        // Arrange
        RequestDelegate appDelegate = async ctx =>
        {
            if (ctx.WebSockets.IsWebSocketRequest)
            {
                var websocket = await ctx.WebSockets.AcceptWebSocketAsync();

                var receiveArray = new byte[1024];
                while (true)
                {
                    var receiveResult = await websocket.ReceiveAsync(new System.ArraySegment <byte>(receiveArray), CancellationToken.None);

                    var sendBuffer = new System.ArraySegment <byte>(receiveArray, 0, receiveResult.Count);
                    await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
                }
            }
        };
        var builder = new WebHostBuilder().Configure(app =>
        {
            app.Run(appDelegate);
        });
        var server = new TestServer(builder);

        // Act
        var client       = server.CreateWebSocketClient();
        var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);

        var hello = Encoding.UTF8.GetBytes("hello");
        await clientSocket.SendAsync(new System.ArraySegment <byte>(hello), WebSocketMessageType.Text, true, CancellationToken.None);

        // Assert
        var buffer = new byte[1];

        for (var i = 0; i < hello.Length; i++)
        {
            bool last   = i == (hello.Length - 1);
            var  result = await clientSocket.ReceiveAsync(new System.ArraySegment <byte>(buffer), CancellationToken.None);

            Assert.Equal(buffer.Length, result.Count);
            Assert.Equal(buffer[0], hello[i]);
            Assert.Equal(last, result.EndOfMessage);
        }

        clientSocket.Dispose();
    }
Exemple #6
0
    private async System.Threading.Tasks.Task <Response> ReceiveMessage()
    {
        // Receive one web socket message
        System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> > segments = new System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> >();

        try
        {
            while (true)
            {
                byte[] buffer  = new byte[4096];
                var    segment = new System.ArraySegment <byte>(buffer, 0, buffer.Length);
                System.Net.WebSockets.WebSocketReceiveResult rcvResult = await ws.ReceiveAsync(segment, stopServerTokenSource.Token);

                // Accumulate the byte arrays in a list, we will join them later
                segments.Add(segment.Skip(segment.Offset).Take(rcvResult.Count));

                if (rcvResult.EndOfMessage)
                {
                    break;
                }
            }
        }
        catch (System.Net.WebSockets.WebSocketException e)
        {
            throw e.InnerException;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error receiving response from server.");
        }

        try
        {
            byte[] bytes = segments.SelectMany(t => t).ToArray <byte>();
            string msg   = System.Text.Encoding.UTF8.GetString(bytes);
            return(Parse(msg));
        }
        catch (ErrorException e)
        {
            // Dispatch already built error
            throw e;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error while parsing response from server.");
        }
    }
Exemple #7
0
    public async Task WebSocketAcceptThrowsWhenCancelled()
    {
        // Arrange
        // This logger will attempt to access information from HttpRequest once the HttpContext is created
        var             logger      = new VerifierLogger();
        RequestDelegate appDelegate = async ctx =>
        {
            if (ctx.WebSockets.IsWebSocketRequest)
            {
                var websocket = await ctx.WebSockets.AcceptWebSocketAsync();

                var receiveArray = new byte[1024];
                while (true)
                {
                    var receiveResult = await websocket.ReceiveAsync(new ArraySegment <byte>(receiveArray), CancellationToken.None);

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);

                        break;
                    }
                    else
                    {
                        var sendBuffer = new System.ArraySegment <byte>(receiveArray, 0, receiveResult.Count);
                        await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
                    }
                }
            }
        };
        var builder = new WebHostBuilder()
                      .ConfigureServices(services => services.AddSingleton <ILogger <IWebHost> >(logger))
                      .Configure(app => app.Run(appDelegate));
        var server = new TestServer(builder);

        // Act
        var client      = server.CreateWebSocketClient();
        var tokenSource = new CancellationTokenSource();

        tokenSource.Cancel();

        // Assert
        await Assert.ThrowsAnyAsync <OperationCanceledException>(async() => await client.ConnectAsync(new Uri("http://localhost"), tokenSource.Token));
    }
Exemple #8
0
        public static Library Decode(System.ArraySegment <byte> record)
        {
            var reader = BebopReader.From(record);

            return(__DecodeFrom(ref reader));
        }
Exemple #9
0
        public static T DecodeAs <T>(System.ArraySegment <byte> record) where T : BaseLibrary, new()
        {
            var reader = BebopReader.From(record);

            return(__DecodeFrom <T>(ref reader));
        }
Exemple #10
0
    public async Task WebSocketWorks()
    {
        // Arrange
        // This logger will attempt to access information from HttpRequest once the HttpContext is created
        var             logger      = new VerifierLogger();
        RequestDelegate appDelegate = async ctx =>
        {
            if (ctx.WebSockets.IsWebSocketRequest)
            {
                Assert.False(ctx.Request.Headers.ContainsKey(HeaderNames.SecWebSocketProtocol));
                var websocket = await ctx.WebSockets.AcceptWebSocketAsync();

                var receiveArray = new byte[1024];
                while (true)
                {
                    var receiveResult = await websocket.ReceiveAsync(new System.ArraySegment <byte>(receiveArray), CancellationToken.None);

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);

                        break;
                    }
                    else
                    {
                        var sendBuffer = new System.ArraySegment <byte>(receiveArray, 0, receiveResult.Count);
                        await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
                    }
                }
            }
        };
        var builder = new WebHostBuilder()
                      .ConfigureServices(services =>
        {
            services.AddSingleton <ILogger <IWebHost> >(logger);
        })
                      .Configure(app =>
        {
            app.Run(appDelegate);
        });
        var server = new TestServer(builder);

        // Act
        var client = server.CreateWebSocketClient();
        // The HttpContext will be created and the logger will make sure that the HttpRequest exists and contains reasonable values
        var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);

        var hello = Encoding.UTF8.GetBytes("hello");
        await clientSocket.SendAsync(new System.ArraySegment <byte>(hello), WebSocketMessageType.Text, true, CancellationToken.None);

        var world = Encoding.UTF8.GetBytes("world!");
        await clientSocket.SendAsync(new System.ArraySegment <byte>(world), WebSocketMessageType.Binary, true, CancellationToken.None);

        await clientSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);

        // Assert
        Assert.Equal(WebSocketState.CloseSent, clientSocket.State);

        var buffer = new byte[1024];
        var result = await clientSocket.ReceiveAsync(new System.ArraySegment <byte>(buffer), CancellationToken.None);

        Assert.Equal(hello.Length, result.Count);
        Assert.True(hello.SequenceEqual(buffer.Take(hello.Length)));
        Assert.Equal(WebSocketMessageType.Text, result.MessageType);

        result = await clientSocket.ReceiveAsync(new System.ArraySegment <byte>(buffer), CancellationToken.None);

        Assert.Equal(world.Length, result.Count);
        Assert.True(world.SequenceEqual(buffer.Take(world.Length)));
        Assert.Equal(WebSocketMessageType.Binary, result.MessageType);

        result = await clientSocket.ReceiveAsync(new System.ArraySegment <byte>(buffer), CancellationToken.None);

        Assert.Equal(WebSocketMessageType.Close, result.MessageType);
        Assert.Equal(WebSocketState.Closed, clientSocket.State);

        clientSocket.Dispose();
    }