Example #1
0
        private async Task ListenerHandler()
        {
            listener.Listen(int.MaxValue);

            while (!isStopped)
            {
                SocketAwaitable     socketAwaitable = null;
                ArraySegment <byte> buffer          = new ArraySegment <byte>();

                try
                {
                    socketAwaitable = socketAwaitablePool.Take();
                    socketAwaitable.Clear();

                    buffer = bufferManager.GetBuffer();
                    socketAwaitable.Buffer = buffer;

                    var result = await listener.AcceptAsync(socketAwaitable);

                    if (result != SocketError.Success || socketAwaitable.AcceptSocket == null)
                    {
                        if (logger.IsDebugEnabled)
                        {
                            logger.Debug("Received error when accepting connection result[{0}]", result);
                        }

                        continue;
                    }

                    var socket = socketAwaitable.AcceptSocket;

                    logger.Info("Received connection from {0}", socket.RemoteEndPoint.ToString());

                    socket.NoDelay     = true;
                    socket.SendTimeout = 1000;

                    var session = socketSessionFactory.CreateAsyncSocketSession(socket.RemoteEndPoint.ToString(), socket);

                    session.PacketMaker.Append(socketAwaitable.Transferred);

                    Add(session);
                }
                catch (SocketException e)
                {
                    logger.Info(e, "SocketException in ListenerHandler. Ignoring...");

                    continue;
                }
                catch (Exception e)
                {
                    logger.Warn(e, "Exception in ListenerHandler");

                    throw;
                }
                finally
                {
                    if (socketAwaitable != null)
                    {
                        socketAwaitable.Clear();
                        socketAwaitablePool.Add(socketAwaitable);
                    }

                    if (buffer.Array != null)
                    {
                        bufferManager.ReleaseBuffer(buffer);
                    }
                }
            }
        }
Example #2
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();
            }
        }