Exemplo n.º 1
0
        public static ChannelMessage ToPacket(this Message message, PacketService packets, long accountId)
        {
            Packet prototype = packets.Packets[message.PacketId];

            if (prototype == null)
            {
                throw new ArgumentException($"Could not find packet {message.PacketId:x2}", nameof(message));
            }

            if (!(prototype is ChannelMessage protoMessage))
            {
                throw new ArgumentException($"Packet {message.PacketId:x2} is not a channel message", nameof(message));
            }

            ChannelMessage packet = (ChannelMessage)prototype.Create();

            packet.Id            = message.PacketId;
            packet.PacketVersion = message.PacketVersion;
            packet.ChannelId     = message.ChannelId;
            packet.SenderId      = message.SenderId ?? 0;
            packet.MessageId     = message.MessageId;
            packet.SkipCount     = 0; // TODO: Implement flags and skip count
            packet.DispatchTime  = DateTime.SpecifyKind(message.DispatchTime, DateTimeKind.Local);
            packet.MessageFlags  = message.MessageFlags;
            packet.FileId        = 0; // Files are not implemented yet
            packet.PacketContent = message.PacketContent;

            packet.Dependencies.AddRange(message.Dependencies
                                         .Where(d => d.AccountId == null || d.AccountId == accountId)
                                         .Select(d => new Dependency(d.AccountId ?? 0, d.MessageId)));

            return(packet);
        }
Exemplo n.º 2
0
        private void OnReceiveMessage(object sender, Hik.Communication.Scs.Communication.Messages.MessageEventArgs e)
        {
            var message = (AuthMessage)e.Message;

            Buffer = message.Data;

            if (PacketService.HasRecvPacket(message.OpCode))
            {
                var packetType    = PacketService.GetRecvPacketType(message.OpCode);
                var packetHandler = (ClientReceivePacket)Activator.CreateInstance(packetType);

                try
                {
                    packetHandler.Process(this);
                }
                catch
                {
                    Log.Error($"Error when handle packet {message.OpCode:X4}:{_client}");
                }
            }
            else
            {
                Log.Error($"No Handler for OPC: {message.OpCode:X4}, Length={Buffer.Length}");
            }
        }
Exemplo n.º 3
0
        public override void LoadContent()
        {
            TransitionOffTime = new TimeSpan(0, 0, 0, 3);
            _timer.Completed += DoStuff;

            PacketService.RegisterPacket <SessionSendSimulationStatePacket>(Handler);

            _bg   = ScreenManager.Game.Content.GetTexture(@"Screens\Title\bg", ScreenManager.Game.GraphicsDevice);
            _logo = ScreenManager.Game.Content.GetTexture(@"bmo_logo", ScreenManager.Game.GraphicsDevice);

            // Send off a packet
            var list = Environment.GetCommandLineArgs().ToList();


            _myToken = Guid.Parse(list[1]);
            string[] info = list[2].Split(Convert.ToChar(":"));

#if DEBUG_MOCK
            info[0] = "localhost" +
                      "";
            info[1]  = "7798";
            _myToken = Guid.Empty;

            Thread.Sleep(6000);
#endif

            NetworkManager.Instance.ConnectTo(info[0], int.Parse(info[1]));

            base.LoadContent();
        }
        public async Task PrepareTest()
        {
            serviceProvider = FakeServiceProvider.Create($"{nameof(DeliveryServiceTests)}_{TestContext.TestName}");
            scope           = serviceProvider.CreateScope();
            connections     = scope.ServiceProvider.GetRequiredService <ConnectionsService>();
            packets         = scope.ServiceProvider.GetRequiredService <PacketService>();
            database        = scope.ServiceProvider.GetRequiredService <DatabaseContext>();
            delivery        = scope.ServiceProvider.GetRequiredService <DeliveryService>();

            database.Accounts.Add(new Account {
                AccountId = alice
            });
            database.MailConfirmations.Add(new MailConfirmation {
                AccountId = alice, MailAddress = "*****@*****.**", Token = SkynetRandom.String(10)
            });
            database.Accounts.Add(new Account {
                AccountId = bob
            });
            database.MailConfirmations.Add(new MailConfirmation {
                AccountId = bob, MailAddress = "*****@*****.**", Token = SkynetRandom.String(10)
            });
            database.Accounts.Add(new Account {
                AccountId = charlie
            });
            database.MailConfirmations.Add(new MailConfirmation {
                AccountId = charlie, MailAddress = "*****@*****.**", Token = SkynetRandom.String(10)
            });
            await database.SaveChangesAsync().ConfigureAwait(false);
        }
Exemplo n.º 5
0
        private void send_btn_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient();

            client.Connect(IP, Port);
            ns = client.GetStream();
            connect_lbl.Text = client.Client.Connected.ToString();
            PacketService ps = new PacketService(Encoding.Default.GetBytes(data_tb.Text), false);

            ps.SetPacketType((PType.PacketType)Enum.Parse(typeof(PType.PacketType), packetType_cb.Text));

            if (packetType_cb.SelectedIndex == 0)
            {
                ps.SetPacketInformationType((PType.MessagePacketType)Enum.Parse(typeof(PType.MessagePacketType), packetPType_cb.Text));
            }
            else if (packetPType_cb.SelectedIndex == 1)
            {
                ps.SetPacketInformationType((PType.SessionPacketType)Enum.Parse(typeof(PType.SessionPacketType), packetPType_cb.Text));
            }

            Packet p = ps.MakePacket();

            ns.Write(p.BData, 0, p.BData.Length);
            responce_lb.Items.Add(Encoding.Default.GetString(p.BData));
            ns.Close();
            client.Close();
        }
Exemplo n.º 6
0
 public void Init(IClient client, DatabaseContext database, PacketService packets, DeliveryService delivery)
 {
     Client   = client;
     Database = database;
     Packets  = packets;
     Delivery = delivery;
 }
Exemplo n.º 7
0
        public Server(ILog logger, string ipAddress, int port)
        {
            _logger = logger;
            Port    = port;
            Host    = ipAddress;

            _clients      = new Dictionary <Guid, IInternalClient>();
            PacketService = new TCPServerPacketService();
            BanIps        = new List <string>();
            BanUsers      = new List <string>();

            BuildBanList();

            try
            {
                _logger.Info("Start ManageServer at {0}:{1}...", Category.System, Host, Port);
                _server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(Host, Port));

                _server.ClientConnected += OnConnected;
            }
            catch (Exception ex)
            {
                _logger?.Exception(ex, "Start ManagementServer");
            }
        }
Exemplo n.º 8
0
        private async static void Listen()
        {
            await Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        TcpClient client = listener.AcceptTcpClientAsync().Result;
                        Console.WriteLine($"Client was connected");
                        NetworkStream nw = client.GetStream();

                        StringBuilder sb = new StringBuilder();
                        int bytes        = 0;
                        byte[] buffer    = new byte[1024];
                        do
                        {
                            bytes = nw.Read(buffer, 0, buffer.Length);
                        } while (nw.DataAvailable);

                        IPEndPoint ep = (IPEndPoint)client.Client.RemoteEndPoint;
                        Packet packet = PacketService.GetPacket(buffer);
                        string ptype  = packet.PT == PType.PacketType.Message ? packet.MPT.ToString() : packet.SPT.ToString();
                        Console.WriteLine($"{ep.Address} => [{packet.PT}] [{ptype}] {packet.SData}");
                    }
                    catch
                    {
                        continue;
                    }
                }
            });
        }
Exemplo n.º 9
0
        public PuzzleGame()
            : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory              = "Content";
            graphics.PreferredBackBufferWidth  = 800;
            graphics.PreferredBackBufferHeight = 600;
            Window.Title             = "Blasters Online";
            graphics.GraphicsProfile = GraphicsProfile.HiDef;



            PacketService.RegisterPacket <SessionEndedLobbyPacket>(Instance_ClientDisconnected);

            foreach (var launchParameter in Environment.GetCommandLineArgs())
            {
                Console.Write(launchParameter);
            }

            // Time to hook the exception reporter if not connected to a debugger
            if (!Debugger.IsAttached)
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
        }
 public ClientSendPacket(IClient connection)
 {
     Connection = connection;
     Log        = connection.Log;
     OpCodes    = connection.PacketService;
     Buffer     = new ByteBuffer();
 }
Exemplo n.º 11
0
 private void button6_Click(object sender, EventArgs e)
 {
     PacketService.sendPacket(
         Process.GetProcessById(procId).Handle,
         procId,
         GoldService.AddGoldSellPacket(Int32.Parse(textBox7.Text), Int32.Parse(textBox8.Text))
         );
 }
 /// <summary>
 /// Creates a new asynchronous stream of a necessary packets to create a direct channel which waits for channel creation.
 /// </summary>
 /// <param name="packets">An instance of packet factory.</param>
 /// <param name="channelCreation">A <see cref="Task{TResult}"/> representing a database operation which will be awaited before emitting the first packet.</param>
 /// <param name="otherId">Bob's account ID which will be shared with Alice.</param>
 /// <param name="otherChannelId">Bob's account data channel ID which will be shared with Alice.</param>
 /// <param name="tempChannelId">If specified the stream returns a <see cref="P2FCreateChannelResponse"/> packet instead of <see cref="P0ACreateChannel"/>.</param>
 public CreateChannelEnumerable(PacketService packets, Task <Channel> channelCreation, long otherId, long otherChannelId, long tempChannelId = default)
 {
     this.packets         = packets;
     this.channelCreation = channelCreation;
     this.otherId         = otherId;
     this.otherChannelId  = otherChannelId;
     this.tempChannelId   = tempChannelId;
 }
Exemplo n.º 13
0
 private void button7_Click(object sender, EventArgs e)
 {
     PacketService.sendPacket(
         Process.GetProcessById(procId).Handle,
         procId,
         GoldService.CancelGoldBuyPacket(Int32.Parse(textBox9.Text), Int32.Parse(textBox10.Text))
         );
 }
Exemplo n.º 14
0
        public GameSessionSimulationService()
        {
            PacketService.RegisterPacket <NotifySessionBeginAppServerPacket>(ProccessIncomingSession);
            PacketService.RegisterPacket <NotifyLoadedGamePacket>(ProcessGameLoaded);
            PacketService.RegisterPacket <NotifyMovementPacket>(HandleMovementRequest);
            PacketService.RegisterPacket <RequestPlaceBombPacket>(HandleBombRequest);

            ActiveGameSessions = new List <SimulatedGameSession>();
        }
Exemplo n.º 15
0
        private string PacketReceive(HttpContext context)
        {
            string userid    = context.Request["userid"] ?? "";
            string packetkey = context.Request["packetkey"] ?? "";
            string type      = context.Request["type"] ?? "";

            string message = string.Empty;

            if (string.IsNullOrEmpty(userid))
            {
                return(ResultJson(ResultType.error, "用户ID不能为空", ""));
            }

            if (string.IsNullOrEmpty(packetkey))
            {
                return(ResultJson(ResultType.error, "请输入红包key", ""));
            }

            if (string.IsNullOrEmpty(type))
            {
                return(ResultJson(ResultType.error, "红包类型不能为空", ""));
            }

            int _type = 0;

            int.TryParse(type, out _type);

            if (!(_type == 1 || _type == 2))
            {
                return(ResultJson(ResultType.error, "红包类型无效", ""));
            }

            long _userid    = 0;
            long _receiveid = 0;

            long.TryParse(userid, out _userid);

            string receiveid;

            try
            {
                receiveid = AESEncrypt.Decrypt(packetkey);
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog("PacketReceive" + ex.ToString(), "packet");
                return(ResultJson(ResultType.error, "红包KEY无效", ""));
            }

            long.TryParse(receiveid, out _receiveid);
            LogHelper.SaveLog(string.Format("PacketReceive -> userid:{0},receiveid:{1},type:{2}", _userid, _receiveid, _type), "packet");
            PacketService svc    = new PacketService();
            var           result = svc.PacketReceive(_userid, _receiveid, _type, out message);

            return(ResultJson(ResultType.success, "ok", result));
        }
Exemplo n.º 16
0
        public Form1()
        {
            InitializeComponent();


            // Register network callbacks
            PacketService.RegisterPacket <SessionListInformationPacket>(ProcessSessionInformation);
            PacketService.RegisterPacket <SessionJoinResultPacket>(ProcessJoinResult);
            PacketService.RegisterPacket <ChatPacket>(ProcessChatPacket);
            PacketService.RegisterPacket <SessionBeginNotificationPacket>(ProcessSessionBegin);
        }
Exemplo n.º 17
0
        public GameSessionService()
        {
            Sessions = new ObservableCollection <GameSession>();

            Sessions.CollectionChanged += SessionsOnCollectionChanged;

            // Register network callbacks
            PacketService.RegisterPacket <SessionJoinRequestPacket>(ProcessSessionJoinRequest);
            PacketService.RegisterPacket <SessionEndedLobbyPacket>(ProcessSessionEnded);
            PacketService.RegisterPacket <SessionCreateRequestPacket>(ProcessSessionCreate);
            PacketService.RegisterPacket <SessionLeaveRequest>(ProcessSessionLeave);
        }
Exemplo n.º 18
0
        public override void OnViewAppeared()
        {
            FlowController.WebControl.Source = new Uri(Environment.CurrentDirectory + @"\" + VIEW_PATH_HTML);

            PacketService.RegisterPacket <SessionJoinResultPacket>(ProcessJoinResult);


            _model      = new RoomSelectModel();
            _controller = new RoomSelectController(_model, this);


            FlowController.WebControl.DocumentReady += WebControlOnDocumentReady;
        }
Exemplo n.º 19
0
        public override void OnViewAppeared()
        {
            FlowController.WebControl.Source = new Uri(Environment.CurrentDirectory + @"\" + VIEW_PATH_HTML);


            PacketService.RegisterPacket <ChatPacket>(ProcessChatPacket);
            PacketService.RegisterPacket <SessionBeginNotificationPacket>(Handler);
            PacketService.RegisterPacket <SessionEndedLobbyPacket>(Handler);

            _model = new RoomSelectModel();



            FlowController.WebControl.DocumentReady += WebControlOnDocumentReady;
        }
Exemplo n.º 20
0
        public Client(IServiceProvider serviceProvider, ConnectionsService connections, PacketService packets, ILogger <Client> logger,
                      PacketStream stream, CancellationToken ct)
        {
            this.serviceProvider = serviceProvider;
            this.connections     = connections;
            this.packets         = packets;
            this.logger          = logger;

            this.stream = stream;
            this.ct     = ct;
            sendQueue   = new JobQueue <Packet, bool>(async(packet, dispose) =>
            {
                try
                {
                    using var buffer = new PacketBuffer();
                    packet.WritePacket(buffer, PacketRole.Server);
                    await stream.WriteAsync(packet.Id, buffer.GetBuffer()).ConfigureAwait(false);
                    logger.LogInformation("Successfully sent packet {0} to session {1}", packet, SessionId.ToString("x8"));
                }
                catch (IOException ex) when(ex.InnerException is SocketException socketEx)
                {
                    await DisposeAsync(waitForHandling: false).ConfigureAwait(false);
                    if (socketEx.SocketErrorCode == SocketError.TimedOut)
                    {
                        logger.LogInformation("Session {0} timed out", SessionId.ToString("x8"));
                    }
                    else
                    {
                        logger.LogInformation("Session {0} lost connection", SessionId.ToString("x8"));
                    }
                }
                catch (Exception ex)
                {
                    await DisposeAsync(waitForHandling: false).ConfigureAwait(false);
                    logger.LogCritical(ex, "Unexpected exception occurred while sending packet {0} to session {1}",
                                       packet.Id.ToString("x2"), SessionId.ToString("x8"));
                }
                finally
                {
                    if (dispose)
                    {
                        (packet as IDisposable)?.Dispose();
                    }
                }
            });
            handler = Listen();
        }
Exemplo n.º 21
0
        public void Process(IInternalClient connection)
        {
            Buffer = new ByteBuffer(connection.Buffer);

            Connection = connection;
            Log        = Connection.Log;
            OpCodes    = connection.PacketService;

            try
            {
                Read();
            }
            catch (Exception ex)
            {
                Log?.Exception(ex, GetType().UnderlyingSystemType.Name);
            }
        }
        public InternalClient(Guid guid, ILog log, IScsServerClient client, string ip, PacketService packetService, IServer server)
        {
            Guid = guid;

            Log           = log;
            _client       = client;
            IP            = ip;
            _server       = server;
            PacketService = packetService;

            _client.WireProtocol = new AuthProtocol();

            _client.Disconnected    += OnTCPDisconnected;
            _client.MessageReceived += OnReceiveMessage;

            ThreadExtension.DelayAndExecute(WaitForFirstPacket, WaitTime);
        }
Exemplo n.º 23
0
        private string PacketList(HttpContext context)
        {
            string userid = context.Request["userid"] ?? "";

            if (string.IsNullOrEmpty(userid))
            {
                return(ResultJson(ResultType.error, "用户ID不能为空", ""));
            }

            long _userid = 0;

            long.TryParse(userid, out _userid);

            PacketService svc    = new PacketService();
            var           result = svc.PacketList(_userid);

            return(ResultJson(ResultType.success, "ok", result));
        }
Exemplo n.º 24
0
        public async Task Should_Only_Return_Plans_For_Your_Facility()
        {
            _factory = new FakeHttpClientFactory(JsonConvert.SerializeObject(Plans), HttpStatusCode.OK);
            _service = new PacketService(config, _factory);

            var plans = await _service.GetPlans(One);

            Assert.True(plans.Count() == 2);


            _factory = new FakeHttpClientFactory(JsonConvert.SerializeObject(Plans), HttpStatusCode.OK);
            _service = new PacketService(config, _factory);

            var plansTwo = await _service.GetPlans(Two);

            Assert.True(plansTwo.Count() == 1);
            Assert.True((plansTwo.First() as PacketPlan).Name == "plan 1");
        }
Exemplo n.º 25
0
        public override void Initialize()
        {
            // Hook into networks events
            PacketService.RegisterPacket <MovementRecievedPacket>(MovementRecieved);

            // Query for the players we don't want
            foreach (var entity in ServiceManager.Entities)
            {
                if (entity.ID == _idToMonitor)
                {
                    continue;
                }

                var transformComponent = (TransformComponent)entity.GetComponent(typeof(TransformComponent));

                var interpolator = new EntityInterpolator(transformComponent);
                _entityInterpolators.Add(entity.ID, interpolator);
            }
        }
Exemplo n.º 26
0
 public void Initialize()
 {
     packets = new PacketService();
 }
Exemplo n.º 27
0
 void RegisterNetworkCallbacks()
 {
     PacketService.RegisterPacket <LoginRequestPacket>(ProcessLoginRequest);
 }
Exemplo n.º 28
0
 static void Main(string[] args)
 {
     PacketService.RegisterPacket <FooPacket>(HandleFooPacket);
 }
Exemplo n.º 29
0
 public UserIntentService()
 {
     // Register our intent packets
     PacketService.RegisterPacket <UserIntentChangePacket>(Handler);
 }
 public AddModel(PacketService packetService)
 {
     _packetService = packetService;
 }