Example #1
0
 public AsyncSocketSession(string remoteIp, Socket socket, IProcessor processor, SocketAwaitablePool socketAwaitablePool, BlockingBufferManager bufferManager)
     : base(remoteIp, processor)
 {
     this.socketAwaitablePool = socketAwaitablePool;
     this.bufferManager       = bufferManager;
     Socket = socket;
 }
Example #2
0
        public SystemVariablesUpdater(IWorld world,
                                      ITribeManager tribeManager,
                                      IDbManager dbManager,
                                      IScheduler scheduler,
                                      IStrongholdManager strongholdManager,
                                      IForestManager forestManager,
                                      ISystemVariableManager systemVariableManager,
                                      INetworkServer networkServer,
                                      IChannel channel,
                                      BlockingBufferManager bufferManager,
                                      SocketAwaitablePool socketAwaitablePool)
        {
            this.world                 = world;
            this.tribeManager          = tribeManager;
            this.dbManager             = dbManager;
            this.scheduler             = scheduler;
            this.strongholdManager     = strongholdManager;
            this.forestManager         = forestManager;
            this.systemVariableManager = systemVariableManager;
            this.networkServer         = networkServer;
            this.channel               = channel;
            this.bufferManager         = bufferManager;
            this.socketAwaitablePool   = socketAwaitablePool;

            if (!string.IsNullOrEmpty(Config.api_id))
            {
                graphiteKeyPrefix = string.Format("servers.{0}_tribalhero_com.tribalhero.", Config.api_id);
            }
        }
        public void TestConcurrentAccess()
        {
            int count = 20;

            // Initialize using a specific count.
            var pool = new SocketAwaitablePool(count);

            Assert.AreEqual(pool.Count, count);

            // Deplete the pool.
            Parallel.For(0, count, i => Assert.IsNotNull(pool.Take()));
            Assert.AreEqual(pool.Count, 0);

            // Force pool to initialize new awaitables.
            var newAwaitables = new SocketAwaitable[count];

            Parallel.For(0, count, i => Assert.IsNotNull(newAwaitables[i] = pool.Take()));

            // Add new awaitables [back] to the pool.
            Parallel.For(0, count, i => pool.Add(newAwaitables[i]));
            Assert.AreEqual(pool.Count, count);

            // Add to, take from and iterate the pool in parallel.
            var addTask = Task.Run(
                () => Parallel.For(0, 1000000, i => pool.Add(new SocketAwaitable())));

            var takeTask = Task.Run(
                () => Parallel.For(0, 1000000 + count, i => Assert.IsNotNull(pool.Take())));

            var iterateTask = Task.Run(
                () => Parallel.ForEach(pool, e => Assert.IsNotNull(e)));

            Task.WaitAll(addTask, takeTask, iterateTask);
        }
        public void TestTakingAfterDispose()
        {
            var pool = new SocketAwaitablePool();

            pool.Dispose();
            pool.Take();
        }
        public void TestConcurrentAccess()
        {
            int count = 20;

            // Initialize using a specific count.
            var pool = new SocketAwaitablePool(count);
            Assert.AreEqual(pool.Count, count);

            // Deplete the pool.
            Parallel.For(0, count, i => Assert.IsNotNull(pool.Take()));
            Assert.AreEqual(pool.Count, 0);

            // Force pool to initialize new awaitables.
            var newAwaitables = new SocketAwaitable[count];
            Parallel.For(0, count, i => Assert.IsNotNull(newAwaitables[i] = pool.Take()));

            // Add new awaitables [back] to the pool.
            Parallel.For(0, count, i => pool.Add(newAwaitables[i]));
            Assert.AreEqual(pool.Count, count);

            // Add to, take from and iterate the pool in parallel.
            var addTask = Task.Run(
                () => Parallel.For(0, 1000000, i => pool.Add(new SocketAwaitable())));

            var takeTask = Task.Run(
                () => Parallel.For(0, 1000000 + count, i => Assert.IsNotNull(pool.Take())));

            var iterateTask = Task.Run(
                () => Parallel.ForEach(pool, e => Assert.IsNotNull(e)));

            Task.WaitAll(addTask, takeTask, iterateTask);
        }
Example #6
0
        private static void Run()
        {
            socketAwaitablePool   = new SocketAwaitablePool(50);
            blockingBufferManager = new BlockingBufferManager(1000, 50);

            while (true)
            {
                try
                {
                    var policySession = Connect();

                    policySession.SendAsyncImmediatelly(Encoding.UTF8.GetBytes("<policy-file-request/>\n")).Wait();

                    var newSession = Connect();

                    var loginPacket = new Packet(Command.Login);
                    loginPacket.AddInt16(0); // version
                    loginPacket.AddInt16(0); // revision
                    loginPacket.AddByte(0);
                    loginPacket.AddString("1234");
                    loginPacket.AddString("");
                    newSession.SendAsyncImmediatelly(loginPacket.GetBytes()).Wait();

                    policySession.Socket.Shutdown(SocketShutdown.Both);
                    policySession.Socket.Close();

                    newSession.Socket.Shutdown(SocketShutdown.Both);
                    newSession.Socket.Close();
                }
                catch (Exception) { }
            }
        }
Example #7
0
        public AsyncSocketConnectionHelper(int bufferSize = 1000, int bufferCount = 15)
        {
            listener              = new TcpListener(IPAddress.Loopback, 0);
            SocketAwaitablePool   = new SocketAwaitablePool(bufferCount);
            BlockingBufferManager = new BlockingBufferManager(bufferSize, bufferCount);

            listener.Start();
        }
        public void TestCopyingToValidArray()
        {
            var p = new SocketAwaitablePool(1) as ICollection;
            var a = new SocketAwaitable[1];

            p.CopyTo(a, 0);
            Assert.IsNotNull(a[0]);
        }
        public RiakOnTheFlyConnection(IRiakNodeConfiguration nodeConfig, int bufferPoolSize = 20)
        {
            _nodeConfig    = nodeConfig;
            _serverUrl     = @"{0}://{1}:{2}".Fmt(nodeConfig.RestScheme, nodeConfig.HostAddress, nodeConfig.RestPort);
            _pool          = new SocketAwaitablePool(nodeConfig.PoolSize);
            _bufferManager = new BlockingBufferManager(nodeConfig.BufferSize, bufferPoolSize);

            _resources = new BlockingLimitedList <RiakPbcSocket>(bufferPoolSize);
        }
        public void TestIteratingAfterDispose()
        {
            var pool = new SocketAwaitablePool();

            pool.Dispose();
            foreach (var awaitable in pool)
            {
            }
        }
        public RiakOnTheFlyConnection(IRiakNodeConfiguration nodeConfig, int bufferPoolSize = 20)
        {
            _nodeConfig = nodeConfig;
            _serverUrl = @"{0}://{1}:{2}".Fmt(nodeConfig.RestScheme, nodeConfig.HostAddress, nodeConfig.RestPort);
            _pool = new SocketAwaitablePool(nodeConfig.PoolSize);
            _bufferManager = new BlockingBufferManager(nodeConfig.BufferSize, bufferPoolSize);

            _resources = new BlockingLimitedList<RiakPbcSocket>(bufferPoolSize);
        }
        public void TestCopyingAfterDispose()
        {
            var pool = new SocketAwaitablePool(1);

            pool.Dispose();

            var array = new SocketAwaitable[1];

            (pool as ICollection).CopyTo(array, 0);
        }
        public void TestLockingSyncRoot()
        {
            var r = new Random();
            var p = new SocketAwaitablePool(r.Next(1000000)) as ICollection;

            Assert.AreEqual(p.IsSynchronized, false);
            lock (p.SyncRoot)
            {
                Assert.Fail("This should never execute.");
            }
        }
        public void TestInitialization()
        {
            int count = 20;

            // Initialize using a valid count.
            var pool = new SocketAwaitablePool(count);
            Assert.AreEqual(pool.Count, count);

            // Initialize using the default count.
            pool = new SocketAwaitablePool();
            Assert.AreEqual(pool.Count, 0);

            // Initialize using an invalid count.
            pool = new SocketAwaitablePool(-1);
        }
Example #15
0
 public RiakPbcSocket(string server, int port, int receiveTimeout, int sendTimeout, int idleTimeout,
                      SocketAwaitablePool socketAwaitablePool, BlockingBufferManager blockingBufferManager,
                      int receiveBufferSize = 8192, int sendBufferSize = 8192, int socketConnectAttempts = 3)
 {
     _endPoint              = new DnsEndPoint(server, port);
     _receiveTimeout        = receiveTimeout;
     _sendTimeout           = sendTimeout;
     _idleTimeout           = new TimeSpan(0, 0, 0, 0, idleTimeout);
     _socketAwaitablePool   = socketAwaitablePool;
     _blockingBufferManager = blockingBufferManager;
     _receiveBufferSize     = receiveBufferSize;
     _sendBufferSize        = sendBufferSize;
     _socketConnectAttempts = socketConnectAttempts;
     _socket = null;
 }
        public void TestInitialization()
        {
            int count = 20;

            // Initialize using a valid count.
            var pool = new SocketAwaitablePool(count);

            Assert.AreEqual(pool.Count, count);

            // Initialize using the default count.
            pool = new SocketAwaitablePool();
            Assert.AreEqual(pool.Count, 0);

            // Initialize using an invalid count.
            pool = new SocketAwaitablePool(-1);
        }
        public void TestAddingAfterDispose()
        {
            var count = 20;
            var pool  = new SocketAwaitablePool(count);

            Assert.AreEqual(pool.Count, count);

            pool.Dispose();
            Assert.AreEqual(pool.Count, 0);

            var awaitable = new SocketAwaitable();

            Assert.IsFalse(awaitable.IsDisposed);

            pool.Add(awaitable);
            Assert.IsTrue(awaitable.IsDisposed);
        }
Example #18
0
        public RiakConnectionPool(IRiakNodeConfiguration nodeConfig)
        {
            _hostAddress         = nodeConfig.HostAddress;
            _poolSize            = nodeConfig.PoolSize;
            _pool                = new SocketAwaitablePool(_poolSize);
            _bufferSize          = nodeConfig.BufferSize;
            _restScheme          = nodeConfig.RestScheme;
            _restPort            = nodeConfig.RestPort;
            _pbcPort             = nodeConfig.PbcPort;
            _networkReadTimeout  = nodeConfig.NetworkReadTimeout;
            _networkWriteTimeout = nodeConfig.NetworkWriteTimeout;
            _idleTimeout         = nodeConfig.IdleTimeout;

            _blockingBufferManager = new BlockingBufferManager(_bufferSize, _poolSize);
            _serverUrl             = @"{0}://{1}:{2}".Fmt(_restScheme, _hostAddress, _restPort);

            Init();
        }
        public RiakConnectionPool(IRiakNodeConfiguration nodeConfig)
        {
            _hostAddress = nodeConfig.HostAddress;
            _poolSize = nodeConfig.PoolSize;
            _pool = new SocketAwaitablePool(_poolSize);
            _bufferSize = nodeConfig.BufferSize;
            _restScheme = nodeConfig.RestScheme;
            _restPort = nodeConfig.RestPort;
            _pbcPort = nodeConfig.PbcPort;
            _networkReadTimeout = nodeConfig.NetworkReadTimeout;
            _networkWriteTimeout = nodeConfig.NetworkWriteTimeout;
            _idleTimeout = nodeConfig.IdleTimeout;
            
            _blockingBufferManager = new BlockingBufferManager(_bufferSize, _poolSize);
            _serverUrl = @"{0}://{1}:{2}".Fmt(_restScheme, _hostAddress, _restPort);

            Init();
        }
        public void TestCopyingToSmallArray()
        {
            var p = new SocketAwaitablePool(2) as ICollection;

            p.CopyTo(new SocketAwaitable[1], 0);
        }
        public void TestCopyingToJaggedArray()
        {
            var p = new SocketAwaitablePool(1) as ICollection;

            p.CopyTo(new SocketAwaitable[1][], 0);
        }
        public void TestCopyingToMultiDimensionalArray()
        {
            var p = new SocketAwaitablePool(1) as ICollection;

            p.CopyTo(new SocketAwaitable[1, 1], 0);
        }
 public void TestCopyingToNullArray()
 {
     var p = new SocketAwaitablePool() as ICollection;
     p.CopyTo(null, 0);
 }
 public void TestCopyingToMultiDimensionalArray()
 {
     var p = new SocketAwaitablePool(1) as ICollection;
     p.CopyTo(new SocketAwaitable[1, 1], 0);
 }
        public void TestCopyingToValidArray()
        {
            var p = new SocketAwaitablePool(1) as ICollection;
            var a = new SocketAwaitable[1];

            p.CopyTo(a, 0);
            Assert.IsNotNull(a[0]);
        }
        public void TestAddingAfterDispose()
        {
            var count = 20;
            var pool = new SocketAwaitablePool(count);
            Assert.AreEqual(pool.Count, count);

            pool.Dispose();
            Assert.AreEqual(pool.Count, 0);

            var awaitable = new SocketAwaitable();
            Assert.IsFalse(awaitable.IsDisposed);

            pool.Add(awaitable);
            Assert.IsTrue(awaitable.IsDisposed);
        }
 public void TestTakingAfterDispose()
 {
     var pool = new SocketAwaitablePool();
     pool.Dispose();
     pool.Take();
 }
 public void TestIteratingAfterDispose()
 {
     var pool = new SocketAwaitablePool();
     pool.Dispose();
     foreach (var awaitable in pool)
     {
     }
 }
 public void TestCopyingToJaggedArray()
 {
     var p = new SocketAwaitablePool(1) as ICollection;
     p.CopyTo(new SocketAwaitable[1][], 0);
 }
 public void TestCopyingToSmallArray()
 {
     var p = new SocketAwaitablePool(2) as ICollection;
     p.CopyTo(new SocketAwaitable[1], 0);
 }
 public void TestCopyingToInt32Array()
 {
     var p = new SocketAwaitablePool(1) as ICollection;
     p.CopyTo(new int[1], 0);
 }
        public void TestCopyingToNullArray()
        {
            var p = new SocketAwaitablePool() as ICollection;

            p.CopyTo(null, 0);
        }
 public void TestCopyingUsingNegativeIndex()
 {
     var p = new SocketAwaitablePool(1) as ICollection;
     p.CopyTo(new SocketAwaitable[1], -1);
 }
        public void TestCopyingUsingNegativeIndex()
        {
            var p = new SocketAwaitablePool(1) as ICollection;

            p.CopyTo(new SocketAwaitable[1], -1);
        }
        public void TestCopyingToInt32Array()
        {
            var p = new SocketAwaitablePool(1) as ICollection;

            p.CopyTo(new int[1], 0);
        }
        public void TestCopyingAfterDispose()
        {
            var pool = new SocketAwaitablePool(1);
            pool.Dispose();

            var array = new SocketAwaitable[1];
            (pool as ICollection).CopyTo(array, 0);
        }
Example #37
0
        public async Task ServerIsAbleToProcessPacketsAndCleansUpResources(ISocketSessionFactory sessionFactory, IProcessor processor, IPlayer player)
        {
            player.GetCityCount().Returns(1);
            player.HasTwoFactorAuthenticated = DateTime.Now;

            var socketAwaitablePool = new SocketAwaitablePool(10);
            var buffer = new BlockingBufferManager(1000, 15);

            Socket             serverSideSocket = null;
            AsyncSocketSession session          = null;

            sessionFactory.CreateAsyncSocketSession(Arg.Any <string>(), Arg.Any <Socket>())
            .Returns(args =>
            {
                serverSideSocket = args.Arg <Socket>();
                session          = new AsyncSocketSession(string.Empty, serverSideSocket, processor, socketAwaitablePool, buffer)
                {
                    Player = player
                };
                return(session);
            });

            AsyncTcpServer server = new AsyncTcpServer(sessionFactory, socketAwaitablePool, buffer);

            try
            {
                server.Start("127.0.0.1", 0);

                // Connect and verify client connected and socket options are set
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true
                };

                var packetToSend1 = new Packet(Command.MarketSell);
                packetToSend1.AddString("Hello");
                var bytesToSendOnConnect = packetToSend1.GetBytes();

                await socket.ConnectAsync(new SocketAwaitable
                {
                    RemoteEndPoint = server.LocalEndPoint
                });

                await Task.Delay(1000);

                await socket.SendAsync(new SocketAwaitable
                {
                    Buffer = new ArraySegment <byte>(bytesToSendOnConnect, 0, bytesToSendOnConnect.Length)
                });

                await Task.Delay(1000);

                server.GetSessionCount().Should().Be(1);
                serverSideSocket.Connected.Should().BeTrue();
                serverSideSocket.NoDelay.Should().BeTrue();
                serverSideSocket.SendTimeout.Should().Be(1000);

                // Send packets and verify server processes packets
                var packetToSend2 = new Packet(Command.MarketBuy);
                packetToSend2.AddString("World");
                var bytesToSecondAfterConnect = packetToSend2.GetBytes();
                await socket.SendAsync(new SocketAwaitable
                {
                    Buffer = new ArraySegment <byte>(bytesToSecondAfterConnect, 0, bytesToSecondAfterConnect.Length)
                });

                await Task.Delay(1000);

                // Stop server and verify it disconnect and releases resources
                server.Stop();

                await Task.Delay(1000);

                player.HasTwoFactorAuthenticated.Should().Be(null);

                serverSideSocket.Connected.Should().BeFalse();
                socketAwaitablePool.Count.Should().Be(10);
                buffer.AvailableBuffers.Should().Be(15);

                processor.Received(1).Execute(session, Arg.Is <Packet>(packet => packet.GetBytes().SequenceEqual(bytesToSecondAfterConnect)));
                processor.Received(1).Execute(session, Arg.Is <Packet>(packet => packet.GetBytes().SequenceEqual(bytesToSendOnConnect)));
                processor.Received(1).ExecuteEvent(session, Arg.Is <Packet>(packet => packet.Cmd == Command.OnDisconnect));
            }
            finally
            {
                server.Stop();
            }
        }
        public void TestLockingSyncRoot()
        {
            var r = new Random();
            var p = new SocketAwaitablePool(r.Next(1000000)) as ICollection;

            Assert.AreEqual(p.IsSynchronized, false);
            lock (p.SyncRoot)
            {
                Assert.Fail("This should never execute.");
            }
        }