public Client( IMediator mediator, IPacketFactory packetFactory) { _mediator = mediator; _packetFactory = packetFactory; }
/// <summary> /// Read and return the next IPacket from the stream /// </summary> public IPacket ReadPacket(Stream packetStream) { m_Reader.ReplaceStream(packetStream); PacketDefinition definition; int typeIndex = (int)m_Reader.ReadUInt32(); if (typeIndex >= m_cachedTypes.Count) { definition = PacketDefinition.ReadPacketDefinition(m_Reader); if (string.IsNullOrEmpty(definition.TypeName)) { //we're hosed... we won't be able to parse this packet. throw new GibraltarSerializationException("The type name of the definition is null, which can't be correct. The packet stream is corrupted.", true); } m_cachedTypes.Add(definition); m_cachedTypes.Commit(); } else { definition = m_cachedTypes[typeIndex]; } definition.PacketCount++; definition.PacketSize += packetStream.Length; IPacketFactory factory = m_PacketFactory.GetPacketFactory(definition.TypeName); IPacket packet = factory.CreatePacket(definition, m_Reader); return(packet); }
/// <summary> /// Reads a single packet from a string. /// </summary> /// <param name="packetFactory">The factory.</param> /// <param name="stream">The stream.</param> /// <returns> /// The parsed packet. /// Returns null if a full packet could not be read. /// </returns> public async Task <IPacket> ReadAsync(IPacketFactory packetFactory, MemoryStream stream) { IPacket packet = null; try { if (!stream.HasRemaining()) { return(null); } packet = await packetFactory.CreateAsync(stream).ConfigureAwait(false); if (null == packet) { return(null); } if (!await packet.DeserializeAsync(stream).ConfigureAwait(false)) { packet = null; return(null); } await stream.CompactAsync().ConfigureAwait(false); return(packet); } finally { if (null == packet) { stream.Reset(); } } }
public DuplicationRoute(int branchALabel, int branchAPort, int branchBLabel, int branchBPort, IPacketFactory packetFactory) { BranchALabel = branchALabel; BranchAPort = branchAPort; BranchBLabel = branchBLabel; BranchBPort = branchBPort; PacketFactory = packetFactory; }
public NetworkController(ISerializer serializer, IPacketFactory packetFactory, GameController gameController) { Serializer = serializer; PacketFactory = packetFactory; PreparePacketFactory(PacketFactory); GameController = gameController; StartClient(); }
/// <summary> /// Read and return the next IPacket from the stream /// </summary> public IPacket Read() { #if ADD_GUARD_BYTES byte[] preamble = new byte[4]; m_Stream.Read(preamble, 0, 4); //now compare it against the preamble. CompareArrays(preamble, PacketWriter.s_PreambleGuardPattern); #endif int packetSize = (int)m_Reader.ReadUInt64(); //if the packet size is less than one, that's obviously wrong if (packetSize < 1) { throw new GibraltarSerializationException("The size of the next packet is smaller than 1 byte or negative, which can't be correct. The packet stream is corrupted.", true); } // TODO: There's got to be a more efficient way to get this done byte[] buffer = new byte[packetSize]; m_Stream.Read(buffer, 0, packetSize); IFieldReader bufferReader = new FieldReader(new MemoryStream(buffer), m_Reader.Strings, m_MajorVersion, m_MinorVersion); PacketDefinition definition; int typeIndex = (int)bufferReader.ReadUInt32(); if (typeIndex >= m_cachedTypes.Count) { definition = PacketDefinition.ReadPacketDefinition(bufferReader); if (string.IsNullOrEmpty(definition.TypeName)) { //we're hosed... we won't be able to parse this packet. throw new GibraltarSerializationException("The type name of the definition is null, which can't be correct. The packet stream is corrupted.", true); } m_cachedTypes.Add(definition); m_cachedTypes.Commit(); } else { definition = m_cachedTypes[typeIndex]; } IPacketFactory factory = m_PacketFactory.GetPacketFactory(definition.TypeName); IPacket packet = factory.CreatePacket(definition, bufferReader); //we used to populate a packet cache here, but a cached packet should be read just once - it shouldn't be in the stream //(and I changed PacketWriter to enforce that) #if ADD_GUARD_BYTES byte[] postamble = new byte[4]; m_Stream.Read(postamble, 0, 4); //now compare it against the preamble. CompareArrays(postamble, PacketWriter.s_PostambleGuardPattern); #endif return(packet); }
public Server( IMediator mediator, IPacketFactory packetFactory, IClientList clientList) { _mediator = mediator; _packetFactory = packetFactory; _clientList = clientList; }
/// <inheritdoc/> /// <summary> /// Initializes a new instance of the <see cref="AuthClient"/> class and binds it with a network session. /// </summary> /// <param name="authenticator">The <see cref="IAuthenticator"/> to use for authenticating the user.</param> /// <param name="nexus">The <see cref="IAuthToNexusRequestHandler"/> to query for... world stuff.</param> /// <param name="serverSession"><inheritdoc/></param> /// <param name="packetFactory"><inheritdoc/></param> /// <param name="logger"><inheritdoc/></param> public AuthClient(IAuthenticator authenticator, IAuthToNexusRequestHandler nexus, IServerSession serverSession, IPacketFactory packetFactory, ILogger logger) : base(serverSession, packetFactory, logger) { this.authenticator = authenticator; this.nexus = nexus; this.LoginAttempts = 0; this.State = AuthClientState.NotLoggedIn; }
public static byte[] PinResponse(this IPacketFactory packetFactory, PinResponseType result) { using (var builder = packetFactory.CreatePacket("PinResponse")) { builder.WriteByte(result); return(builder.ToByteArray()); } }
public PacketSender(IFileHandler fileHandler, IUserExperience userExperience, IPacketFactory packetFactory) { _fileHandler = fileHandler; _userExperience = userExperience; _packetFactory = packetFactory; _allDevices = LivePacketDevice.AllLocalMachine; }
protected PacketTests() { IServiceCollection services = new ServiceCollection(); services.AddImplementingTypes <IPacketCreator>(); services.AddSingleton <IPacketFactory, PacketFactory>(); IServiceProvider provider = services.BuildServiceProvider(); Factory = provider.GetService <IPacketFactory>(); }
public PacketBase <T> CreatePacket <T>(PacketIdDefine id) where T : new() { PacketIdDefine key = id; if (m_Packets.ContainsKey(key)) { IPacketFactory factory = m_Packets[key]; return(factory.CreatePacket() as PacketBase <T>); } LogModule.LogInfo("Can't find packet factory for type : {0}", key); return(null); }
/////////////////////////////////////////////////// // Member Functions /////////////////////////////////////////////////// /// <summary> /// Generic constructor /// </summary> public ClientConn(IPacketFactory factory, T obj) { _logger = null; _factory = factory; _obj = obj; _packetQueue = new Queue <PacketBase>(); _networkLock = new ReaderWriterLock(); _rand = new Random(); }
public NMEASentenceProcessor( IPacketFactory packetFactory, ISentenceListener sentenceListener, ParserConfiguration parserConfiguration, VesselCollection vesselCollection) { _packetFactory = packetFactory; _listener = sentenceListener; _configuration = parserConfiguration; _vessels = vesselCollection; _listener.OnSentenceReceived += _listener_OnSentenceReceived; }
public ReliabilityUdpClient(string hostname, ushort port, Action <ConnectionData> callback, Action <ReceiveCustomDataPacketData> callback2, Action <UdpClient> option = null, IPacketFactory factory = null) { if (factory != null) { _packetFactory = factory; } _connectionCallback = callback; _receiveCustomDataPacketCallback = callback2; _client = new UdpClient(hostname, port); option?.Invoke(_client); }
public ReliabilityUdpClient(IPEndPoint endPoint, Action <ConnectionData> callback, Action <ReceiveCustomDataPacketData> callback2, Action <UdpClient> option = null, IPacketFactory factory = null) { if (factory != null) { _packetFactory = factory; } _connectionCallback = callback; _receiveCustomDataPacketCallback = callback2; _client = new UdpClient(endPoint); option?.Invoke(_client); }
public MQTTPacketDecoder() { _packetFactories = new IPacketFactory[20]; RegisterPacketType <ConnectPacket>(ControlPacketType.CONNECT); RegisterPacketType <PingReqPacket>(ControlPacketType.PINGREQ); RegisterPacketType <DisconnectPacket>(ControlPacketType.DISCONNECT); RegisterPacketType <PublishPacket>(ControlPacketType.PUBLISH); RegisterPacketType <PubAckPacket>(ControlPacketType.PUBACK); RegisterPacketType <PubRecPacket>(ControlPacketType.PUBREC); RegisterPacketType <PubRelPacket>(ControlPacketType.PUBREL); RegisterPacketType <PubCompPacket>(ControlPacketType.PUBCOMP); RegisterPacketType <SubscribePacket>(ControlPacketType.SUBSCRIBE); RegisterPacketType <UnsubscribePacket>(ControlPacketType.UNSUBSCRIBE); }
/////////////////////////////////////////////////// // Member Functions /////////////////////////////////////////////////// /// <summary> /// Generic constructor /// </summary> public Server(IPacketFactory factory, NetworkClient clientTemplate) { _buffer = new byte[4096]; _logger = null; _factory = factory; _clientTemplate = clientTemplate; _packetQueue = new Queue <PacketBase>(); _networkLock = new ReaderWriterLock(); _clients = new Dictionary <long, NetworkClient>(); _rand = new Random(); }
/// <summary> /// Initializes a new instance of the <see cref="ClientBase" /> class. /// </summary> /// <param name="serverSession">The network session to bind the instance to.</param> /// <param name="packetFactory">The <see cref="IPacketFactory" /> to use for this client.</param> /// <param name="logger">The logger to use for this client.</param> /// <exception cref="ArgumentNullException">Thrown if any of the parameters is <see langword="null" />.</exception> protected ClientBase(IServerSession serverSession, IPacketFactory packetFactory, ILogger logger) { Guard.NotNull(() => serverSession, serverSession); Guard.NotNull(() => packetFactory, packetFactory); this.isDisposed = false; this.sentPings = new AtomicInteger(0); this.ServerSession = this.InitializeSession(serverSession); this.PacketFactory = packetFactory; this.Logger = logger; this.keepAliveTimer = this.InitializeTimer(); this.keepAliveTimer.Start(); }
public void ProcessCommands(ConnectManager connMan) { // 一次最多执行10个 for (int i = 0; i < 10; i++) { if (!m_InputStream.HasData()) { return; } int size = m_InputStream.TryReadBuffer(m_temp); //parse packet id and length if (size < 4) { return; } ushort len = BitConverter.ToUInt16(m_temp, 0); ushort packetId = BitConverter.ToUInt16(m_temp, 2); if (size < len) { //还没接收完或者包不完整 return; } m_InputStream.SetReadIndex(len); try { // 调用handle IPacketFactory factory = connMan.GetPacketFactory((Packets.PacketIdDefine)packetId); if (factory != null) { m_tempStream.Seek(0, SeekOrigin.Begin); m_tempStream.SetLength(len - c_headSize); object data = Serializer.Deserialize(factory.GetDataType(), m_tempStream);//GC狂魔 IPacketHandler handler = connMan.GetPacketHandler((Packets.PacketIdDefine)packetId); if (handler != null) { handler.Handle(this, data); } } } catch (Exception e) { LogModule.LogInfo("Handle packet error, Packet id : {0}, len : {1}, msg : {2}", packetId, len, e.Message); Shutdown(); break; } } }
public IRoute Create(IPacketFactory packetFactory) { var programRoute = new ProgrammRoute(); var types = SelectTypes(); foreach (var type in types) { var programRouteId = type.GetCustomAttribute <ProgrammRouteAttribute>().Id; if (typeof(ProgramDuplicationRoute).IsAssignableFrom(type)) { programRoute.RouteProgrammsBases.Add(programRouteId, new ProgramDuplicationRoute(packetFactory)); continue; } programRoute.RouteProgrammsBases.Add(programRouteId, (IProgrammRouteMarker)Activator.CreateInstance(type, new object[] { })); } return(programRoute); }
private static void PreparePacketFactory(IPacketFactory packetFactory) { try { var asd = new LoginFailedHandler(null).GetType().Assembly .GetTypesImplementingGenericClass(typeof(GenericPacketHandlerAsync <>)); foreach (var _packetHandler in asd) { if (!(UsefulContainer.Instance.Resolve(_packetHandler) is IPacketHandler packetHandler)) { continue; } var packetType = _packetHandler.BaseType.GenericTypeArguments[0]; packetFactory.RegisterAsync(packetHandler, packetType).ConfigureAwait(false).GetAwaiter().GetResult(); } } catch (Exception e) { Debug.LogError(e); } }
/// <summary> /// Initializes a new instance of the <see cref="ClientBase" /> class. /// </summary> /// <param name="serverSession">The network session to bind the instance to.</param> /// <param name="packetFactory">The <see cref="IPacketFactory" /> to use for this client.</param> /// <param name="logger">The logger to use for this client.</param> /// <exception cref="ArgumentNullException">Thrown if any of the parameters is <see langword="null" />.</exception> protected ClientBase(IServerSession serverSession, IPacketFactory packetFactory, ILogger logger) { if (serverSession == null) { throw new ArgumentNullException(nameof(serverSession)); } if (packetFactory == null) { throw new ArgumentNullException(nameof(packetFactory)); } _isDisposed = false; _sentPings = new AtomicInteger(0); ServerSession = InitializeSession(serverSession); PacketFactory = packetFactory; Logger = logger; _keepAliveTimer = InitializeTimer(); _keepAliveTimer.Start(); }
private static void Main(string[] args) { packetFactory = new PacketFactory(); users = new Dictionary <IServiceUser, TcpClient>(); string hostName = Dns.GetHostName(); // Retrive the Name of HOST IPAddress myIP = IPAddress.Parse(Dns.GetHostByName(hostName).AddressList[0].ToString()); Int32 port = 4000; server = new TcpListener(myIP, port); server.Start(); BackgroundWorker acceptClientWorker = new BackgroundWorker(); acceptClientWorker.DoWork += AcceptClientWorker_DoWork; acceptClientWorker.RunWorkerAsync(); while (true) { } }
public LoginTcpHandler(IChannel channel, IPacketFactory packetFactory) { _channel = channel; _packetFactory = packetFactory; }
public PacketManager(IPacketSender packetSender, IPacketFactory packetFactory) { _packetSender = packetSender; _packetFactory = packetFactory; }
/// <summary> /// Associates the specified IPacketFactory with a type name /// </summary> /// <param name="typeName">Should refer to a type that implements IPacket</param> /// <param name="factory">IPacketFactory class used to </param> public void RegisterFactory(string typeName, IPacketFactory factory) { m_PacketFactories[typeName] = factory; }
public void RegisterFactory(string typeName, IPacketFactory factory) { m_PacketFactory.RegisterFactory(typeName, factory); }
public MessagePackGameSerializer(IPacketFactory packetFactory /*, IFormatterResolver formatterResolver*/) { PacketFactory = packetFactory; //GeneratedResolver = formatterResolver; }
public LoginUdpPacketHandler(IPacketFactory _packetFactory) { packetFactory = _packetFactory; }
/// <inheritdoc/> public ChannelClient(IServerSession serverSession, IPacketFactory packetFactory, ILogger logger) : base(serverSession, packetFactory, logger) { }
public MsgPackGameSerializer(ILogger log, IPacketFactory packetFactory) { this._packetFactory = packetFactory; _log = log; }
public ClientFactory(IPacketManager packetManager, IPacketFactory packetFactory, INetworkFactory networkFactory) { this.packetManager = packetManager; this.packetFactory = packetFactory; this.networkFactory = networkFactory; }