Exemplo n.º 1
0
        private async Task WriteMemoryStreamAsync(NetworkStream ns, MemoryStream ms, int offset, int length, CancellationToken cancellationToken = default(CancellationToken))
        {
            await ns.WriteAsync(BitConverter.GetBytes(length), 0, sizeof(int), cancellationToken).ConfigureAwait(false);

            await ns.WriteAsync(ms.GetBuffer(), offset, length, cancellationToken).ConfigureAwait(false);

            outboundBytesAggregator.Put(sizeof(int) + length);
        }
Exemplo n.º 2
0
        public async Task <object> ReadPayloadAsync(NetworkStream ns, CancellationToken cancellationToken)
        {
            var lengthBuffer = new byte[sizeof(int)];

            await ReadBytesAsync(ns, sizeof(int), lengthBuffer, cancellationToken).ConfigureAwait(false);

            var frameLength = BitConverter.ToInt32(lengthBuffer, 0);
            var frameBytes  = await ReadBytesAsync(ns, frameLength, null, cancellationToken).ConfigureAwait(false);

            inboundBytesAggregator.Put(sizeof(int) + frameLength);

            return(Deserialize.From(new MemoryStream(frameBytes, 0, frameBytes.Length, false, true)));
        }
Exemplo n.º 3
0
        public int TakeAndResetOutboundMessagesAvailableCounter()
        {
            // Compute time interval represented by this iteration.
            var now = DateTime.Now;
            var dt  = (now - lastIterationTime).TotalSeconds;

            lastIterationTime = now;

            // Update current rate based on dt and rate velocity.
            var deltaMessageRate = (int)(dt * rateVelocity);

            currentRate += deltaMessageRate;
            outboundMessageRateLimitAggregator.Put(currentRate);

            // Compute outbound messages available based on message rate and iteration interval.
            return((int)(currentRate * dt));
        }
Exemplo n.º 4
0
        public void BroadcastThreadStart(Socket socket)
        {
            while (true)
            {
                sema.WaitOne();
//            Console.WriteLine("!!!!!!! " + todo.Count);
                Tuple <MemoryStream, int, int, Action> x;
                if (!todo.TryDequeue(out x))
                {
                    throw new InvalidStateException();
                }
                var s = new ManualResetEvent(false);
                using (var e = new SocketAsyncEventArgs()) {
                    e.RemoteEndPoint = configuration.MulticastSendEndpoint;
                    e.SetBuffer(x.Item1.GetBuffer(), x.Item2, x.Item3);
                    e.Completed += (sender, args) => {
                        s.Set();
                    };
                    try {
                        if (!socket.SendToAsync(e))
                        {
                            // Completed synchronously. e.Completed won't be called.
                            // pooling was leading to leaks?
                        }
                        else
                        {
                            s.WaitOne();
                        }
                    } catch (ObjectDisposedException) when(isShutdown)
                    {
                    }
                    e.SetBuffer(null, 0, 0);
                    x.Item4();
                    outboundBytesAggregator.Put(x.Item3);
                }
            }
        }
Exemplo n.º 5
0
        public static UdpClient Create(UdpTransportConfiguration udpTransportConfiguration, IScheduler udpUnicastScheduler, IObjectPool <byte[]> sendReceiveBufferPool, IAuditAggregator <double> inboundBytesAggregator, IAuditAggregator <double> outboundBytesAggregator, IAuditAggregator <double> inboundReceiveProcessDispatchLatencyAggregator)
        {
            var multicastSockets = new List <Socket>();
            var unicastSockets   = new List <Socket>();

            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (!networkInterface.SupportsMulticast ||
                    networkInterface.OperationalStatus != OperationalStatus.Up ||
                    networkInterface.IsReceiveOnly)
                {
                    continue;
                }

//             HACK loopback disable
                if (networkInterface.Name.Contains("3"))
                {
                    continue;
                }

                var ipv4Properties = networkInterface.GetIPProperties()?.GetIPv4Properties();
                if (ipv4Properties != null)
                {
                    multicastSockets.Add(CreateMulticastSocket(ipv4Properties.Index, udpTransportConfiguration));
                    if (!udpTransportConfiguration.MulticastReceiveEndpoint.Equals(udpTransportConfiguration.UnicastReceiveEndpoint))
                    {
                        unicastSockets.Add(CreateUnicastSocket(ipv4Properties.Index, udpTransportConfiguration));
                    }
                }

                var ni = networkInterface;
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    Console.WriteLine(ni.Name);
                    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            Console.WriteLine(ip.Address.ToString());
                        }
                    }
                }
            }

            var unicastJobQueue = udpUnicastScheduler.CreateJobQueue <UdpUnicastJob>(
                job => {
                var outboundBuffer = job.OutboundBuffer;
                outboundBytesAggregator.Put(outboundBuffer.Length);

                var e            = new SocketAsyncEventArgs();
                e.RemoteEndPoint = job.RemoteInfo.IPEndpoint;
                e.SetBuffer(outboundBuffer.GetBuffer(), 0, (int)outboundBuffer.Position);
                e.Completed += (sender, args) => {
                    // Duplicate code with below.
                    args.SetBuffer(null, 0, 0);
                    args.Dispose();

                    job.SendCompletionHandler();
                };

                const int kSendStateAsync = 1;
                const int kSendStateDone  = 2;
                const int kSendStateError = 3;
                int sendState;
                try {
                    bool completingAsynchronously = job.RemoteInfo.Socket.SendToAsync(e);
                    sendState = completingAsynchronously ? kSendStateAsync : kSendStateDone;
                } catch (ObjectDisposedException) {
                    sendState = kSendStateError;
                }

                if (sendState == kSendStateDone || sendState == kSendStateError)
                {
                    // Completed synchronously so e.Completed won't be called.
                    e.SetBuffer(null, 0, 0);
                    e.Dispose();

                    job.SendCompletionHandler();
                }
            });

            return(new UdpClient(udpTransportConfiguration, multicastSockets, unicastSockets, unicastJobQueue, sendReceiveBufferPool, inboundBytesAggregator, outboundBytesAggregator, inboundReceiveProcessDispatchLatencyAggregator));
        }