public virtual bool Setup(INetServerConfig config, INetApplication application, INetProtocol protocol, ISocketSessionFactory sessionFactory)
        {
            if (protocol == null)
            {
                throw new ArgumentNullException("protocol");
            }
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }

            this.protocol       = protocol;
            this.application    = application;
            this.config         = config;
            this.endPoint       = new IPEndPoint(config.Address, config.Port);
            this.sessionFactory = sessionFactory;

            this.status    = NetServerStatus.Inited;
            this.IsRunning = false;

            return(true);
        }
        public DotNettySocketServer(ILogger <DotNettySocketServer> logger, IFluentSocketApplication app, ISocketSessionBuilder socketSessionBuilder, ServerSetting setting)
        {
            _logger = logger;
            _app    = app;

            _setting = setting;
            if (!_setting.ExtraSettings.Any())
            {
                _setting.ExtraSettings.Add(new DotNettyServerSetting());
            }
            _extraSetting = (DotNettyServerSetting)_setting.ExtraSettings.FirstOrDefault();

            _socketSessionBuilder = socketSessionBuilder;
            _sessionFactory       = app.ServiceProvider.GetService <ISocketSessionFactory>();

            _cts = new CancellationTokenSource();
            _messageReqChannel = Channel.CreateBounded <MessageReqPacketWrapper>(_setting.MessageReqCapacity);

            _requestMessageHandlerDict = new ConcurrentDictionary <short, IRequestMessageHandler>();
            _services       = new ConcurrentDictionary <Type, ISocketService>();
            _pushFutureDict = new ConcurrentDictionary <int, PushFuture>();
            _channelDict    = new ConcurrentDictionary <string, IChannel>();
        }
Example #3
0
 public AsyncTcpServer(ISocketSessionFactory socketSessionFactory, SocketAwaitablePool socketAwaitablePool, BlockingBufferManager bufferManager)
 {
     this.socketSessionFactory = socketSessionFactory;
     this.socketAwaitablePool  = socketAwaitablePool;
     this.bufferManager        = bufferManager;
 }
Example #4
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();
            }
        }
Example #5
0
        public override bool Setup(INetServerConfig config, INetApplication application, INetProtocol protocol, ISocketSessionFactory sessionFactory)
        {
            if (base.Setup(config, application, protocol, sessionFactory))
            {
                Logger = LoggerManager.GetLogger(String.Concat(Application.Name, ".AsyncTcp.", config.Port));
                this.sessionFactory = sessionFactory;
                return(true);
            }

            return(false);
        }
Example #6
0
 public SynchronousTcpServer(ISocketSessionFactory socketFactory)
 {
     this.socketFactory = socketFactory;
     listeningThread    = new Thread(ListenerHandler);
 }
        /// <summary>
        /// 新建一个CommandServer
        /// </summary>
        /// <param name="ipAddress">监听的IP地址,如果传入空对应于IPAddress.Any</param>
        /// <param name="port">监听端口</param>
        /// <param name="appName">应用名称,表示此服务的名称,对功能无关紧要</param>
        /// <param name="serverName">服务名称,表示服务使用的内部TCP监听服务的名称,对功能无关紧要</param>
        /// <param name="useProtocol">所使用的协议</param>
        /// <param name="sessionFactory">创建内部Session的工厂, 注意:工厂所创建的Session必须是WebSocketSession的子类</param>
        public CommandServer(string ipAddress, int port, string appName, string serverName, string useProtocol, ISocketSessionFactory sessionFactory)
        {
            logger = LoggerManager.GetLogger("CommandServer." + (appName == "" ? "UnName" : appName));
            DefaultCommandParser = new WSBinaryCommandType();
            this.SessionFactory  = sessionFactory;

            IP             = ipAddress;
            Port           = port;
            RequestTimeout = TimeSpan.FromMinutes(2);
            SessionList    = new Dictionary <string, CommandSession>();
            Protocol       = useProtocol;
            IsAync         = true;
            CommandList    = new List <ICommand>();

            CommandList.Add(new SetCommandParserRequest());

            CommandParser = new List <ICommandParser>()
            {
                new WSCommandType(),
                new WSBinaryCommandType()
            };

            CommandAliveTime = TimeSpan.FromMinutes(2);

            IPAddress address = IPAddress.Any;

            if (!String.IsNullOrEmpty(ipAddress))
            {
                address = IPAddress.Parse(IP);
            }

            application = new WebSocketApplication();
            application.Setup(appName);
            AsyncTcpServer server = new AsyncTcpServer();

            ServerConfig = new SocketServerConfig()
            {
                Address             = address,
                AddressFamily       = System.Net.Sockets.AddressFamily.InterNetwork,
                MaxConnectionNumber = 1000,
                Name           = serverName,
                Port           = Port,
                SessionTimeout = (long)TimeSpan.FromMinutes(5).TotalMilliseconds,
                TimeoutType    = Dynamic.Net.Session.SessionTimeoutType.Unknown, //不过期
                ServerType     = NetServerType.ASyncTcp
            };
            server.Setup(ServerConfig, application, new WebSocketProtocol(), sessionFactory);


            application.AddServer(server);


            application.SwitchingProtocol += new EventHandler <SwitchingProtocolEventArgs>(SwitchingProtocol);

            application.SessionStarted += new EventHandler(SessionStarted);

            application.SessionClosed      += new EventHandler(SessionClosed);
            application.HandshakeCompleted += new EventHandler(HandshakeCompleted);

            application.MessageReceived += new EventHandler <MessageReceivedEventArgs>(MessageReceived);
        }