Пример #1
0
        public async Task <IReadOnlyCollection <ReadOnlyMemory <byte> > > SendAsync(IReadOnlyCollection <ReadOnlyMemory <byte> > buffers, SwimHost host)
        {
            var output = new byte[_options.MaxDatagramSize];

            var remainingBuffers = new Queue <ReadOnlyMemory <byte> >(buffers);

            var length = 0;

            while (length < _options.MaxDatagramSize && remainingBuffers.Count > 0)
            {
                var buffer = remainingBuffers.Dequeue();

                var lengthDelta = MessagePackBinary.WriteBytes(ref output, length, buffer.ToArray());
                if (length + lengthDelta > _options.MaxDatagramSize)
                {
                    break;
                }

                length += lengthDelta;
            }

            if (length > 0)
            {
                await _udpClient.SendAsync(output, length, host.AsIPEndPoint());
            }

            return(remainingBuffers.ToList());
        }
        private static int SerializeHost(ref byte[] bytes, int offset, SwimHost host)
        {
            var endpoint = host.AsIPEndPoint();

            var length = 0;

            length += MessagePackBinary.WriteBytes(ref bytes, offset + length, endpoint.Address.GetAddressBytes());
            length += MessagePackBinary.WriteUInt16(ref bytes, offset + length, (ushort)endpoint.Port);

            return(length);
        }
Пример #3
0
        public Task StartAsync()
        {
            _udpClient = new UdpClient(_local.AsIPEndPoint());

            if (_listenerThread != null)
            {
                throw new InvalidOperationException();
            }

            _listenerThreadCancel = new CancellationTokenSource();
            _listenerThread       = new Thread(ListenerThread);
            _listenerThread.Start(_listenerThreadCancel.Token);

            return(Task.CompletedTask);
        }