Example #1
0
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException" />
        /// <exception cref="ArgumentOutOfRangeException" />
        public SocketListener(EndPoint listenEndPoint, int backlog, int maxConnections, IPacketProcessor packetProcessor)
        {
            if (listenEndPoint == null)
            {
                throw new ArgumentNullException(nameof(listenEndPoint));
            }
            if (backlog <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(backlog));
            }
            if (maxConnections <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConnections));
            }
            if (packetProcessor == null)
            {
                throw new ArgumentNullException(nameof(packetProcessor));
            }

            this.listenEndPoint         = listenEndPoint;
            this.backlog                = backlog;
            this.maxConnections         = maxConnections;
            this.packetProcessor        = packetProcessor;
            this.sendOperation          = SocketOperation.Asynchronization;
            this.bufferSize             = SocketConstants.DefaultBufferSize;
            this.keepAlive              = KeepAlive.OFF;
            this.maxConnectionsEnforcer = new Semaphore(maxConnections, maxConnections);
            this.statistics             = new SocketListenerStatistics();

            this.acceptEventArgs            = new SocketAsyncEventArgs();
            this.acceptEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(Accept_Completed);
            this.ioEventArgsPool            = new ConcurrentStack <SocketAsyncEventArgs>();
        }
Example #2
0
 public PacketReceiver(IPacketValidator packetValidator, IPacketProcessor packetProcessor, IQdafLogger logger)
 {
     _packetValidator = packetValidator;
     _packetProcessor = packetProcessor;
     _logger = logger;
     _errors = new Lazy<List<string>>(() => new List<string>()); 
 }
Example #3
0
        /// <summary>
        /// Creates a channel and assigns a valid ID, port and manager to it
        /// </summary>
        /// <remarks>
        /// It is recommended to use this method whenever you wish to create a new channel.
        /// The only reason not to use this method is if you wish to create a channel with a specific ID
        /// which may cause issues
        /// </remarks>
        /// <typeparam name="T">The type of channel to create</typeparam>
        /// <returns>Returns a newly created channel ready to be added</returns>
        public T CreateChannel <T>(IPacketProcessor packetProcessor) where T : IServerChannel
        {
            var channel = (T)_channelMgr.CreateChannel <T>();

            channel.PacketProcessor = packetProcessor;
            return(channel);
        }
Example #4
0
        public override void OnReceive(ISocketContext <MqttMessage> context, MqttMessage msg)
        {
            this._logger.LogTrace("receive Packet from {0}", context.RemoteEndPoint);

            if (msg?.Packet == null)
            {
                this._logger.LogWarning("receive receive message from {0}, but packet is null", context.RemoteEndPoint);
                return;
            }

            Task.Run(
                async() =>
            {
                this._logger.LogDebug("receive Packet from {0}, type ={1}", context.RemoteEndPoint, msg.Packet.PacketType);

                MqttClientSession clientSession = this._sessionManager.GetClientSession(context, msg.Packet);

                IPacketProcessor processor = this._processorManager.GetProcessor(msg.Packet.PacketType);
                if (processor != null)
                {
                    MqttMessage rsp = await processor.ProcessAsync(clientSession, msg.Packet);
                    if (rsp != null)
                    {
                        if (rsp.Packet != null)
                        {
                            await context.SendAsync(rsp);
                        }

                        if (rsp.Code != 0)    //主动断开
                        {
                            await ShutdownChannel(context, msg.Packet);
                        }
                    }
                }
                else
                {
                    this._logger.LogWarning("PacketType:{0} has no processor", msg.Packet.PacketType);
                }
            }).ConfigureAwait(false);

            /*
             * switch (msg.Packet.PacketType)
             * {
             *  case  PacketType.CONNECT:
             *      Console.WriteLine("receive connect pack client_id = {0}",((ConnectPacket)msg.Packet).ClientId);
             *      var ack = new ConnAckPacket { ReturnCode = ConnectReturnCode.Accepted, SessionPresent = true};
             *      context.SendAsync(new MqttMessage { Packet =  ack});
             *      break;
             *  case PacketType.PINGREQ:
             *      context.SendAsync(new MqttMessage { Packet =   PingRespPacket.Instance});
             *      break;
             *  default:
             *      Console.WriteLine("receive Packet from {0}, type ={1}",context.RemoteEndPoint,msg.Packet.PacketType);
             *      break;
             *
             * }*/
        }
Example #5
0
        protected AbstractServerStageUser(ISocket socket, IPacketProcessor <TStage, TUser> processor) : base(socket, processor)
        {
            var bytes  = new byte[8];
            var random = new Random();

            random.NextBytes(bytes);

            Key = BitConverter.ToInt64(bytes, 0);
        }
        public NetPacketParserTests()
        {
            _packetProcessor = new NetPacketProcessor();
            _buffer          = new List <int>(new[] { 16, 0, 0, 0, 12, 0, 0, 0, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }).Select(x => (byte)x).ToArray();
            _bufferHeader    = _buffer.Take(_packetProcessor.HeaderSize).ToArray();
            _bufferContent   = _buffer.Skip(_packetProcessor.HeaderSize).ToArray();
            _messageContent  = Encoding.UTF8.GetString(_bufferContent.Skip(sizeof(int)).ToArray());

            _invalidBuffer = new List <int>(new[] { 255, 255, 255, 255, 12, 0, 0, 0, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }).Select(x => (byte)x).ToArray();
        }
Example #7
0
        public PacketRouter(IPacketProcessor processor, IConnectionNegotiator connection)
        {
            RecvRoutingUpdate     = new TrafficCounter();
            RecvVoiceData         = new TrafficCounter();
            RecvTextData          = new TrafficCounter();
            RecvHandshakeResponse = new TrafficCounter();

            _processor  = processor;
            _connection = connection;
        }
Example #8
0
 public UNetClient(IPacketProcessor packetProcessor)
 {
     _channelManager = new ChannelManager();
     PacketProcessor = packetProcessor;
     ActiveChannels  = new List <IClientChannel> {
         CreateMainChannel()
     };
     Identity        = new SocketIdentity(0);
     _operationTable = new Dictionary <int, ISocketOperation>();
 }
        public Task RegisterAsync(IPacketProcessor processor, Type packetType)
        {
            if (_packetProcessors.ContainsKey(packetType))
            {
                return(Task.CompletedTask);
            }

            _packetTypesByHeader.Add(packetType.GetCustomAttribute <PacketHeaderAttribute>().Identification, packetType);
            _packetProcessors[packetType] = processor;
            return(Task.CompletedTask);
        }
Example #10
0
 public HostedTzspListener
 (
     ILogger logger,
     CommandLineArguments commandLineArguments,
     IPacketProcessor packetProcessor
 )
 {
     _logger          = logger.ForContext <HostedTzspListener>();
     _args            = commandLineArguments;
     _packetProcessor = packetProcessor;
 }
Example #11
0
        /// <inheritdoc />
        public TcpClient(IPacketProcessor packetProcessor)
        {
            if (packetProcessor == null)
            {
                throw new ArgumentNullException(nameof(packetProcessor));
            }

            this.packetProcessor = packetProcessor;
            this.bufferSize      = SocketConstants.DefaultBufferSize;
            this.keepAlive       = KeepAlive.OFF;
        }
Example #12
0
        public static void RegisterPacketType(Type type, IPacketProcessor processor)
        {
            if (currentPacketIndex + 1 > byte.MaxValue)
            {
                throw new InvalidOperationException("Cannot register packet type. Not enough space.");
            }

            PacketConverters.Add(type, currentPacketIndex);
            PacketBytes.Add(currentPacketIndex, type);
            Packets.Add(currentPacketIndex, processor);
            currentPacketIndex++;
        }
Example #13
0
        public LoginStage(
            LoginStageConfig config,
            ILogger <IStage <LoginStage, LoginStageUser> > logger,
            IServerRegistry serverRegistry,
            ISessionRegistry sessionRegistry,
            IMigrationRegistry migrationRegistry,
            IGuildService guildService,
            IPartyService partyService,
            IAccountRepository accountRepository,
            IAccountWorldRepository accountWorldRepository,
            ICharacterRepository characterRepository,
            ITickerManager timerManager,
            IPacketProcessor <LoginStage, LoginStageUser> processor,
            ITemplateRepository <WorldTemplate> worldTemplates,
            ITemplateRepository <ItemTemplate> itemTemplates
            ) : base(
                ServerStageType.Login,
                config,
                logger,
                serverRegistry,
                sessionRegistry,
                migrationRegistry,
                accountRepository,
                accountWorldRepository,
                characterRepository,
                timerManager,
                processor
                )
        {
            Logger = logger;

            GuildService = guildService;
            PartyService = partyService;

            WorldTemplates = worldTemplates;
            ItemTemplates  = itemTemplates;

            processor.Register(new CheckPasswordHandler(this));
            processor.Register(new WorldInfoRequestHandler());
            processor.Register(new SelectWorldHandler());
            processor.Register(new CheckUserLimitHandler());
            processor.Register(new SetGenderHandler());
            processor.Register(new CheckPinCodeHandler());
            processor.Register(new WorldRequestHandler());
            processor.Register(new LogoutWorldHandler());
            processor.Register(new CheckDuplicatedIDHandler());
            processor.Register(new CreateNewCharacterHandler());
            processor.Register(new DeleteCharacterHandler());
            processor.Register(new ExceptionLogHandler(this));
            processor.Register(new EnableSPWRequestHandler(false));
            processor.Register(new CheckSPWRequestHandler(false));
        }
Example #14
0
        public Connection(Socket stream, IPacketProcessor[] processors, int bufferSize = 1024 * 6)
        {
            _netStream = stream;
            BufferSize = bufferSize;
            _packetProcessors = processors;

            _readBuffer = new byte[bufferSize];
            _readStream = new MemoryStream(_readBuffer);
            _reader = new BinaryReader(_readStream);

            _writeBuffer = new byte[bufferSize];
            _writeStream = new MemoryStream(_writeBuffer);
            _writer = new BinaryWriter(_writeStream);
        }
        public NetPacketParserTests()
        {
            this._packetProcessor    = new NetPacketProcessor();
            this._packetParser       = new NetPacketParser(this._packetProcessor);
            this._buffer             = new List <int>(new[] { 16, 0, 0, 0, 12, 0, 0, 0, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }).Select(x => (byte)x).ToArray();
            this._bufferHeader       = this._buffer.Take(this._packetProcessor.HeaderSize).ToArray();
            this._bufferContent      = this._buffer.Skip(this._packetProcessor.HeaderSize).ToArray();
            this._bufferContentSize  = this._bufferContent.Take(sizeof(int)).ToArray();
            this._messageSize        = BitConverter.ToInt32(this._bufferHeader);
            this._messageContentSize = BitConverter.ToInt32(this._bufferContentSize) + sizeof(int); // extra int size for string length
            this._messageContent     = Encoding.UTF8.GetString(this._bufferContent.Skip(sizeof(int)).ToArray());

            this._invalidBuffer = new List <int>(new[] { 255, 255, 255, 255, 12, 0, 0, 0, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }).Select(x => (byte)x).ToArray();
        }
Example #16
0
        private void InternalProcess(GameClient Client, byte[] Packet)
        {
            fixed(byte *pPacket = Packet)
            {
                ushort *Size = (ushort *)(pPacket + 0);
                ushort *Type = (ushort *)(pPacket + 2);

                if (*Size != Packet.Length)
                {
                    SizeMismatch(Client, *Size, Packet);
                    return;
                }

                Kernel.HexDump(Packet, "Client -> Server");

                IPacketProcessor processor = null;

                switch (*Type)
                {
                case 0x3E9: processor = new CreateCharacterProcessor(Database); break;

                case 0x3EC: processor = new ChatProcessor(Database, CommandProcessor, NpcScriptEngine); break;

                case 0x3ED: processor = new MovementProcessor(Database); break;

                case 0x3F1: processor = new ItemUsageProcessor(Database); break;

                case 0x3F2: processor = new GeneralDataProcessor(Database); break;

                case 0x3FE: processor = new AttackProcessor(Database); break;

                case 0x41C: processor = new LoginTransferProcessor(Database); break;

                case 0x7EF:
                case 0x7F0:
                    processor = new NpcProcessor(Database, NpcScriptEngine);
                    break;

                default:
                    Client.Send(Packet);
                    break;
                }

                if (processor != null)
                {
                    processor.Execute(Client, pPacket);
                }
            }
        }
Example #17
0
        public BattleServer(string host, int port)
        {
            Configuration.Backlog = 50;
            Configuration.Host    = host;
            Configuration.Port    = port;
            Configuration.MaximumNumberOfConnections = 2; // Spectators allowed but not yet
            Configuration.BufferSize = 1024;
            Configuration.Blocking   = true;

            battle                 = new PBEBattle(PBEBattleFormat.Double, PBESettings.DefaultSettings);
            battle.OnNewEvent     += PBEBattle.ConsoleBattleEventHandler;
            battle.OnNewEvent     += BattleEventHandler;
            battle.OnStateChanged += BattleStateHandler;
            PacketProcessor        = new PBEPacketProcessor(battle);
        }
Example #18
0
        public static IPacketProcessor InstantiatePacketProcessor(Type type, IDictionary <string, string> argsDict)
        {
            // Predicate determining if a parameter could be provided
            Func <ParameterInfo, bool> parameterIsAvailable = param =>
                                                              argsDict.ContainsKey(param.Name) && IsAllowedConstructorParameterType(param.ParameterType);
            // Predicate determining if a constructor can be called
            Func <ConstructorInfo, bool> constructorCanBeCalled = ctor =>
                                                                  ctor.GetParameters().All(p => parameterIsAvailable(p) || p.IsOptional);

            // Get the constructors for this type that we could call with the given arguments:
            var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)
                               .Where(constructorCanBeCalled);

            // Try to instantiate the type, using the best constructor we can:
            // Prefer constructors where we can provide all the parameters to those where some will be their default values
            var sortedConstructors = constructors.OrderByDescending(ctor => ctor.GetParameters().Length)
                                     .ThenByDescending(ctor => ctor.GetParameters().Count(p => !p.IsOptional));

            foreach (var constructor in sortedConstructors)
            {
                try
                {
                    // Get the arguments for the constructor, converted to the proper types
                    var arguments = GetArgumentsForConstructor(constructor, argsDict).ToArray();
                    // Invoke the constructor, instantiating the type
#if MOREDEBUG
                    Console.WriteLine("Invoking new {0}", ConstructorString(constructor, arguments));
#endif
                    IPacketProcessor pp = (IPacketProcessor)constructor.Invoke(arguments);
                    return(pp);
                }
                catch (Exception ex) when(ex is InvalidCastException ||
                                          ex is FormatException ||
                                          ex is KeyNotFoundException)
                {
                    // If an exception is thrown, ignore it and try the next best constructor
                    // But log it first:
                    Debug.WriteLine("Constructor failed - {0}:", constructor.ToString());
                    Debug.WriteLine(ex);
                }
            }

            // If we reach this point, there were no constructors that we could use
            Console.WriteLine("No suitable constructor could be found.");
            return(null);
        }
Example #19
0
File: Test.cs Project: niksu/pax
    public Nested_Chained_Test2()
    {
        mirror_cfg = Mirror.InitialConfig(PaxConfig_Lite.no_interfaces);
        Debug.Assert(PaxConfig_Lite.no_interfaces >= 3);
        mirror_cfg[0] = new ForwardingDecision.SinglePortForward(2); // Mirror port 0 to port 2

        this.pp =
            new PacketProcessor_Chain(new List <IPacketProcessor>()
        {
            /* FIXME would be tidier to use this
             *        new Mirror(
             *          Mirror.InitialConfig(PaxConfig_Lite.no_interfaces).MirrorPort(0, 2)
             *          ),
             */
            new Mirror(mirror_cfg),
            new LearningSwitch(),
        });
    }
Example #20
0
        public void Process(GameSession session, IPacket packet)
        {
            IPacketProcessor processor = processors.GetValue(packet.GetType());

            if (processor == null)
            {
                return;
            }

            try
            {
                processor.Process(session, packet);
            }
            catch (Exception e)
            {
                Log.Error($"Error when processing packet {packet.GetType().Name}", e);
            }
        }
Example #21
0
 private void Reset()
 {
     resetEvent.Reset();
     state = ServerState.Resetting;
     foreach (Player c in readyPlayers.ToArray())
     {
         DisconnectClient(c.Id);
         c.ResetEvent.Close();
     }
     battle                 = new PBEBattle(PBEBattleFormat.Double, PBESettings.DefaultSettings);
     battle.OnNewEvent     += PBEBattle.ConsoleBattleEventHandler;
     battle.OnNewEvent     += BattleEventHandler;
     battle.OnStateChanged += BattleStateHandler;
     packetProcessor        = new PBEPacketProcessor(battle);
     battlers               = null;
     spectatorPackets.Clear();
     state = ServerState.WaitingForPlayers;
     resetEvent.Set();
 }
Example #22
0
        public void Process(IClient client, IPacket packet)
        {
            IPacketProcessor processor = processors.GetValueOrDefault(packet.GetType());

            if (processor == null)
            {
                Logger.Warn($"No packet processor for {packet.GetType().Name}");
                return;
            }

            Logger.Trace($"Processing packet {packet.GetType().Name} using {processor.GetType().Name}");
            try
            {
                processor.Process(client, packet);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Example #23
0
File: Pax.cs Project: niksu/pax
        private static IPacketProcessor InstantiatePacketProcessor(Type type)
        {
#if MOREDEBUG
            Console.WriteLine("Trying to instantiate {0}", type);
#endif

            // Get the constructor arguments for this type from the config
            IDictionary <string, string> arguments =
                PaxConfig.configFile.handlers?.Where(handler => type.Name.Equals(handler.class_name))
                .Select(intf => intf.args)
                .SingleOrDefault();
            if (arguments == null)
            {
                arguments = new Dictionary <string, string>();
            }

#if MOREDEBUG
            Console.WriteLine("  Arguments:");
            foreach (var pair in arguments)
            {
                Console.WriteLine("    {0} : {1}", pair.Key, pair.Value);
            }
            Console.WriteLine("  Public constructors:");
            foreach (var ctor in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public))
            {
                Console.WriteLine("    {0}", PacketProcessorHelper.ConstructorString(ctor));
            }
#endif

            // Instantiate the packet processor
            IPacketProcessor pp = PacketProcessorHelper.InstantiatePacketProcessor(type, arguments);
            if (pp == null)
            {
                Console.WriteLine("Couldn't instantiate {0}", type.FullName);
            }

            check_version_exc(pp);

            return(pp);
        }
Example #24
0
 public void AddProcessor(IPacketProcessor processor)
 {
     processor.RegisterProcessor(new PacketProcessorConfig(_handlers, _defaultProcessors));
 }
Example #25
0
 /// <inheritdoc />
 public void SetPacketProcessor(IPacketProcessor packetProcessor)
 {
     _packetParser.PacketProcessor = packetProcessor;
 }
Example #26
0
 /// <summary>
 /// Creates a new <see cref="NetReceiver"/> instance.
 /// </summary>
 /// <param name="packetProcessor">Default packet processor.</param>
 public NetReceiver(IPacketProcessor packetProcessor)
 {
     _packetParser = new NetPacketParser(packetProcessor);
 }
Example #27
0
 public TextDumper(IPacketProcessor <Nothing> inner, StringBuilder sb)
 {
     this.inner = new NothingToBoolProcessor(inner);
     this.sb    = sb;
 }
Example #28
0
 public TextDumper(IPacketProcessor <bool> inner, StringBuilder sb)
 {
     this.inner = inner;
     this.sb    = sb;
 }
Example #29
0
 public LoginStageUser(ISocket socket, IPacketProcessor <LoginStage, LoginStageUser> processor) : base(socket, processor)
 {
     IsLoggingIn = true;
     State       = LoginState.LoggedOut;
 }
Example #30
0
 public NetManager(IPacketProcessor p_PacketProcessor)
 {
     m_PlayerManager   = Game.Instance.PlayerManager;
     m_PacketProcessor = p_PacketProcessor;
 }
Example #31
0
 /// <summary>
 /// Creates a new <see cref="NetPacketParser"/> instance.
 /// </summary>
 /// <param name="packetProcessor">Net packet processor used to parse the incoming data.</param>
 public NetPacketParser(IPacketProcessor packetProcessor)
 {
     this.PacketProcessor = packetProcessor;
 }
Example #32
0
 /// <inheritdoc />
 public SocketListener(int port, int backlog, int maxConnections, IPacketProcessor packetProcessor)
     : this(new IPEndPoint(IPAddress.Any, port), backlog, maxConnections, packetProcessor)
 {
 }