Пример #1
0
        public void Start(int port, CancellationToken cancellationToken = default)
        {
            if (cancellationToken == default)
            {
                _source           = new CancellationTokenSource();
                cancellationToken = _source.Token;
            }

            _address  = $"tcp://*:{port}";
            _outgoing = new ResponseSocket();

            var options = new SocketOptions(_outgoing);

            _protocol.Configure(options);
            _outgoing.Bind(_address);
            _out?.WriteInfoLine($"{_id}: Bound to {_address}");

            _task = Task.Run(() =>
            {
                EstablishHandshake();

                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        if (_outgoing.IsDisposed)
                        {
                            continue;
                        }
                        if (!_outgoing.TryReceiveFrameBytes(_interval, out var message))
                        {
                            continue;
                        }
                        _protocol.OnMessageReceived(_outgoing, message);
                    }
                    catch (Exception e)
                    {
                        _out?.WriteErrorLine($"{_id}: Error during message receive loop: {e}");
                        break;
                    }
                }

                _stopping.Set();
            }, cancellationToken);
        }