예제 #1
0
        public KestrelRequestHandler(Func <WsStream, Task> connectionAdded, int bufferSize, CancellationToken stopToken,
                                     string defaultPage = Config.Version)
        {
            // create a raw middleware
            _wsMiddleware = new WebSocketMiddleware(async ctx =>
            {
                if (ctx.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await ctx.WebSockets.AcceptWebSocketAsync();
                    var sId             = Guid.NewGuid();
                    await webSocket.SendAsync(new ArraySegment <byte>(sId.ToByteArray()), WebSocketMessageType.Binary,
                                              true, CancellationToken.None);
                    var wsc = new WsStream(new WStreamBaseSocket(webSocket, true), sId);
                    // dont block the current task
#pragma warning disable 4014
                    Task.Run(() => connectionAdded.Invoke(wsc));
#pragma warning restore 4014
                    while (webSocket.State == WebSocketState.Open && !stopToken.IsCancellationRequested)
                    {
                        await Task.Delay(100);
                    }

                    wsc.Close();
                }
                else
                {
                    await ctx.Response.WriteAsync(defaultPage);
                }
            }, Options.Create(new WebSocketOptions()
            {
                ReceiveBufferSize = bufferSize
            }), NullLoggerFactory.Instance);
        }
예제 #2
0
        /// <summary>
        /// Connect to the websocket server
        /// </summary>
        /// <param name="uri">The uri of the server</param>
        /// <returns>A new websocket connection</returns>
        /// <exception cref="EndOfStreamException">Thrown when the websocket gets disconnected while initializing</exception>
        public async Task <WsStream> ConnectAsync(Uri uri)
        {
            await _client.ConnectAsync(uri, CancellationToken.None);

            var bytes   = new byte[16];
            int lenRead = 0;

            while (lenRead < 16)
            {
                var res = await _client.ReceiveAsync(
                    new ArraySegment <byte>(bytes, lenRead, 16 - lenRead), CancellationToken.None);

                if (res.Count == 0)
                {
                    throw new EndOfStreamException("Unexpected end of Websocket while initializing");
                }
                lenRead += res.Count;
            }
            return(_connection = new WsStream(new WStreamBaseSocket(_client, false), new Guid(bytes)));
        }