Exemplo n.º 1
0
        public override void Start()
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseUrls($"http://{_options.Listen.Address}:{_options.Listen.Port}")
                       .ConfigureServices(services =>
            {
                services.AddSingleton <IWebSocketHandler>(_socketHandler);
            })
                       .UseStartup <Startup>()
                       .Build();

            host.Start();

            this._resources.Add(host);

            _options.EndPoints.ForEach(async endPoint =>
            {
                var ws = new ClientWebSocket();
                ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
                await ws.ConnectAsync(new Uri($"ws://{endPoint.Address}:{endPoint.Port}"), CancellationToken.None);

                _connectionManager.AddSocket(ws);
                await _socketHandler.OnStart(ws);
                await ws.ReceiveAsync(_socketHandler);
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Handle websocket connection
        /// </summary>
        /// <param name="socket">socket</param>
        /// <param name="cancellationToken">Cancellation token</param>
        public async Task HandleAsync(IdentifiableWebSocket socket, CancellationToken cancellationToken)
        {
            _webSocketConnectionManager.AddSocket(socket);

            await Receive(socket,
                          async (result, buffer) =>
            {
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    await OnMessageReceive(socket, result, buffer, cancellationToken);
                    return;
                }
                else if (result.MessageType == WebSocketMessageType.Close)
                {
                    await OnDisconnected(socket, cancellationToken);
                    return;
                }
            },
                          async (socket) =>
            {
                await OnDisconnected(socket, cancellationToken);
            },
                          cancellationToken
                          );
        }