Exemplo n.º 1
0
        async Task EchoLoop()
        {
            _cts = new CancellationTokenSource();

            try
            {
                var buffer = new byte[BufferSize];
                var seg    = new ArraySegment <byte>(buffer);

                while (this._socket.State == WebSocketState.Open || _cts.Token.IsCancellationRequested)
                {
                    try
                    {
                        if (!_isInitialized)
                        {
                            _isInitialized = true;
                            ClientId       = RegisterNewClient();
                        }
                        await Task.Delay(1);

                        var incoming = await this._socket.ReceiveAsync(seg, _cts.Token);

                        if (_cts.Token.IsCancellationRequested)
                        {
                            break;
                        }

                        if (incoming.MessageType == WebSocketMessageType.Binary)
                        {
                            _gameServer.NotifyMessageRecieved(ClientId, ref buffer, incoming.Count);
                        }
                    }
                    catch (OperationCanceledException ce)
                    {
                        Logger.Log(ce);
                        break;
                    }
                    catch (WebSocketException wse)
                    {
                        Logger.Log(wse);
                        break;
                    }
                    catch (Exception e)
                    {
                        Logger.Log(e);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
            finally
            {
                if (ClientId != 0)
                {
                    RemoveClient(ClientId);
                }
            }
        }