Пример #1
0
        private void InitializeEnvironment()
        {
            _map = new ClientMap();

            _syncScroll = new object();

            _fpsCounterData = new byte[10];
            _fpsFontBrush   = new SolidBrush(Color.White);

            _playersData = new Dictionary <int, PlayerDataEx>();

            _threadWorld = new Thread(WorldProcessingProc);
            _threadWorld.IsBackground = true;
            _threadWorld.Start();

            _threadObjectChanged = new Thread(ObjectChangedProc);
            _threadObjectChanged.IsBackground = true;
            _threadObjectChanged.Start();

            TCPClientSettings settings = new TCPClientSettings
                                         (
                ushort.MaxValue, "127.0.0.1", 15051, true
                                         );

            _tcpClient               = new TCPClient(settings);
            _tcpClient.Connected    += TCPConnected;
            _tcpClient.DataReceived += TCPDataReceived;
            _tcpClient.Disconnected += TCPDisconnected;
        }
Пример #2
0
        public void Render(MapControl mapCtrl, Graphics buffer, Rectangle area)
        {
            if (mapCtrl.Map == null)
            {
                return;
            }

            float     scale     = mapCtrl.ScaleFactor;
            float     pixelSize = ConstMap.PIXEL_SIZE * scale;
            ClientMap map       = mapCtrl.Map;

            ushort mapX1 = (ushort)Math.Max(Math.Floor(mapCtrl.PosX / pixelSize - 1), 0);
            ushort mapY1 = (ushort)Math.Max(Math.Floor(mapCtrl.PosY / pixelSize - 1), 0);
            ushort mapX2 = (ushort)Math.Min(Math.Ceiling(mapCtrl.Width / scale / pixelSize + 2) + mapX1, map.Width);
            ushort mapY2 = (ushort)Math.Min(Math.Ceiling(mapCtrl.Height / scale / pixelSize + 2) + mapY1, map.Height);

            for (ushort y = mapY1; y < mapY2; y++)
            {
                for (ushort x = mapX1; x < mapX2; x++)
                {
                    Tile *tile = map[x, y];
                    if (tile != null && (*tile).Type == TileType.Wall)
                    {
                        float      pixXToRealX = x * pixelSize - mapCtrl.PosX;
                        float      pixXToRealY = y * pixelSize - mapCtrl.PosY;
                        RectangleF rect        = new RectangleF(
                            pixXToRealX - -0,
                            pixXToRealY - -0,
                            pixelSize + -0,
                            pixelSize + -0);
                        buffer.FillRectangle(_fillBrush, rect);
                    }
                }
            }
        }
        public static void Render(GameEngine engine, GraphicsRenderer renderer, ClientMap map, GameTime gameTime)
        {
            Dictionary <int, List <CoreAbstractEntity> > sortedEntities = GetEntitiesByTilePosition(map);

            (ClientMapTile tile, Vector2 position) = GetHighlightedTile(engine, map);

            renderer.Start();
            for (int i = 0; i < map.Width * map.Height; ++i)
            {
                int   tileX = i % map.Width;
                int   tileY = i / map.Width;
                float drawX = tileX * ClientMapTile.TILE_WIDTH;
                float drawY = tileY * ClientMapTile.TILE_HEIGHT;

                MapTileRenderer.Render(engine, renderer, gameTime, map[i], drawX, drawY);
                if (tile != null && tileX == (int)position.X && tileY == (int)position.Y)
                {
                    renderer.Render(AssetRegistry.TILE_SELECTION, drawX, drawY);
                }

                if (sortedEntities.ContainsKey(i))
                {
                    RenderEntities(engine, renderer, gameTime, sortedEntities[i], map[i], drawX, drawY);
                }
            }

            renderer.Finish();
        }
 public static void Update(GameEngine engine, GameTime gameTime, ClientMap map)
 {
     for (int i = 0; i < map.Width * map.Height; i++)
     {
         MapTileRenderer.Update(engine, gameTime, map[i]);
     }
 }
Пример #5
0
        public static void Update(GameEngine engine, ClientGameEnvironment clientEnvironment, GameTime gameTime)
        {
            ClientMap map = clientEnvironment.Map;

            if (map != null)
            {
                MapRenderer.Update(engine, gameTime, map);
            }
        }
Пример #6
0
        public static void Render(GameEngine engine, GraphicsRenderer renderer,
                                  ClientGameEnvironment clientEnvironment, GameTime gameTime)
        {
            ClientMap map = clientEnvironment.Map;

            if (map != null)
            {
                MapRenderer.Render(engine, renderer, map, gameTime);
            }
        }
Пример #7
0
        public static bool IsOppositeTile(int x, int y, ushort w, ushort h, TileType areaType,
                                          ClientMap map)
        {
            if (x < 0 || x >= w || y < 0 || y >= h)
            {
                return(true);
            }
            Tile *tile;

            return((tile = map[(ushort)x, (ushort)y]) != null && (*tile).Type != areaType);
        }
Пример #8
0
        public void Execute(HttpRequest httpRequest, JsonPacket jsonRequest, SessionComponent session)
        {
            // Connect
            NetworkChannel channel = new NetworkChannel(Connection);

            // Request
            JsonBrowseRequestMessage jsonRequestMessage = JsonBrowseRequestMessage.Parse(jsonRequest.Message);

            JsonClient jsonClient = jsonRequestMessage.Client;

            if (jsonClient == null)
            {
                channel.SendNotFound();
                return;
            }

            Entity entity = ClientMap.Get(jsonClient.Id);

            if (entity == null)
            {
                channel.SendNotFound();
                return;
            }

            // Command
            TunnelComponent      tunnel  = entity.Get <TunnelComponent>();
            BrowseRequestCommand command = new BrowseRequestCommand(entity, tunnel.Connection);
            string jsonData = command.Execute(jsonRequest.Data);

            if (string.IsNullOrEmpty(jsonData))
            {
                channel.SendNotFound();
                return;
            }

            // Response
            JsonBrowseResponseMessage jsonResponseMessage = new JsonBrowseResponseMessage();
            JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage, jsonData);

            HttpResponse httpResponse = new HttpResponse()
            {
                Data = session.Encrypt(jsonResponse)
            };

            channel.Send(httpResponse);
#if DEBUG
            Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
        }
Пример #9
0
        public void Map_MapsClientGetDtoToClient()
        {
            ClientGetDto clientGetDto = new ClientGetDto
            {
                Name = "Test",
                Id   = 1
            };

            Client    client;
            ClientMap clientMap = new ClientMap();

            clientMap.Map(clientGetDto, out client);

            Assert.Equal("Test", client.Name);
            Assert.Equal(1, client.Id);
        }
Пример #10
0
        public void Map_MapsClientToClientCreateDto()
        {
            Client client = new Client
            {
                Id   = 1,
                Name = "Test"
            };

            ClientCreateDto clientCreateDto;
            ClientMap       clientMap = new ClientMap();

            clientMap.Map(client, out clientCreateDto);

            Assert.Equal("Test", client.Name);
            Assert.Equal(1, client.Id);
        }
Пример #11
0
        public void Render(MapControl mapCtrl, Graphics buffer, Rectangle area)
        {
            ClientMap map    = mapCtrl.Map;
            Player    player = mapCtrl.PlayerData;

            if (map == null || player == null)
            {
                return;
            }

            int posX = (int)(player.Position.X + player.Size.Width / 2 - area.X - _fovRect.Width / 2);
            int posY = (int)(player.Position.Y + player.Size.Height / 2 - area.Y - _fovRect.Height / 2);

            float pSizeW = _fovBitmap.Width, pSizeHw = (float)_fovBitmap.Width / 2;
            float pSizeH = _fovBitmap.Height, pSizeHh = (float)_fovBitmap.Height / 2;

            if (player.Angle != _prewPlayerAngle)
            {
                _fovRotated.Clear(Color.FromArgb(0, 0, 0, 0));
                _fovRotated.TranslateTransform(pSizeHw, pSizeHh);
                _fovRotated.RotateTransform(player.Angle - _prewPlayerAngle);
                _fovRotated.TranslateTransform(-pSizeHw, -pSizeHh);
                _fovRotated.DrawImage(_fovBitmap, 0, 0);
                _prewPlayerAngle = player.Angle;
            }

            buffer.DrawImage(_fovRotatedBitmap, posX, posY, _fovRect, GraphicsUnit.Pixel);

            if (posX > 0)
            {
                buffer.FillRectangle(_fillBrush, new Rectangle(0, 0, posX, area.Height));
            }
            if (posY > 0)
            {
                buffer.FillRectangle(_fillBrush, new Rectangle(posX, 0, area.Width - posX, posY));
            }
            if (posX + _fovRect.Width < area.X + area.Width)
            {
                buffer.FillRectangle(_fillBrush, new Rectangle((int)(posX + _fovRect.Width), posY,
                                                               area.Width - posX, area.Height - posY));
            }
            if (posY + _fovRect.Height < area.Y + area.Height)
            {
                buffer.FillRectangle(_fillBrush, new Rectangle(posX, (int)(posY + _fovRect.Height),
                                                               area.Width - posX, area.Height - posY));
            }
        }
Пример #12
0
        /// <summary>
        /// Listens for packets from a client and manages that client's connection status.
        /// </summary>
        /// <param name="client"></param>
        private void Handle(TcpClientHandler client)
        {
            if (ConnectedEvent != null)
            {
                ConnectedEvent(client);
            }

            Stopwatch watch = new Stopwatch();

            watch.Start();

            while (client.Connected)
            {
                if (watch.ElapsedMilliseconds >= client.Timeout)
                {
                    if (AttemptReconnectEvent != null)
                    {
                        AttemptReconnectEvent(client);
                    }
                    client.Connected = client.Receiver.Connected;
                }

                if (client.Stream.DataAvailable)
                {
                    int          packet = client.Receiver.Available;
                    BufferStream buffer = new BufferStream(packet, 1);
                    if (client.Receiver.Connected)
                    {
                        client.Stream.Read(buffer.Memory, 0, packet);
                    }
                    if (ReceivedEvent != null)
                    {
                        ReceivedEvent(client, buffer);
                    }
                }

                watch.Reset();
            }

            if (DisconnectedEvent != null)
            {
                DisconnectedEvent(client);
            }
            ClientMap.Remove(client.Socket);
            client.Close();
        }
Пример #13
0
        public void Map_MapsClientCreateDtoToClient()
        {
            ClientCreateDto clientCreateDto = new ClientCreateDto
            {
                Name     = "Test",
                Password = "******"
            };

            Client client;

            ClientMap clientMap = new ClientMap();

            clientMap.Map(clientCreateDto, out client);

            Assert.Equal("Test", client.Name);
            Assert.Equal(0, client.Id);
        }
Пример #14
0
        /// <summary>
        /// Accepts pending client connections and begins listening for packets on each accepted client.
        /// </summary>
        private void Accept()
        {
            running = true;
            if (StartedEvent != null)
            {
                StartedEvent(this);
            }

            while (Status)
            {
                if (!Listener.Pending())
                {
                    continue;
                }

                TcpClientHandler client = (ClientCreatedEvent != null) ? ClientCreatedEvent(Binder, this, ClientTimeout) : new TcpClientHandler(Binder, this, ClientTimeout);
                client.Receiver  = Listener.AcceptTcpClient();
                client.Connected = true;

                if ((ClientMap.Count <= MaxConnections && MaxConnections >= 0) || MaxConnections <= 0)
                {
                    TcpClient receiver = client.Receiver;
                    receiver.LingerState = new LingerOption(false, 0);
                    receiver.NoDelay     = true;
                    client.Stream        = receiver.GetStream();
                    ClientMap.Add(client.Socket, client);
                    ThreadPool.QueueUserWorkItem(thread => Handle(client));
                }
                else
                {
                    if (ClientOverflowEvent != null)
                    {
                        ThreadPool.QueueUserWorkItem(thread => ClientOverflowEvent(client));
                    }
                    client.Close();
                }
            }

            if (ClosedEvent != null)
            {
                ClosedEvent(this);
            }
            running = false;
            Close();
        }
Пример #15
0
        public void TestCreateMapWithHelper([Values(false, true)] bool accessUsingInterface)
        {
            //--Act
            var clientMap = new ClientMap();

            DisplayTableMapColumns(clientMap);

            //--Assert
            Assert.AreEqual("Client", clientMap.TableName);

            var id = clientMap[typeof(IGuidIdentifier).GetProperty(nameof(IGuidIdentifier.Id))];

            Assert.AreEqual("Id", id.ColumnName);
            Assert.AreEqual(ColumnBehavior.Key | ColumnBehavior.Generated, id.Behavior);
            Assert.AreEqual(SqlOperation.Insert | SqlOperation.Update, id.IgnoreOperations);

            var createdByUserId = clientMap[(accessUsingInterface ? typeof(ICreateFields) : typeof(Client)).GetProperty(nameof(Client.CreatedByUserId))];

            Assert.AreEqual("CreatedByUserId", createdByUserId.ColumnName);
            Assert.AreEqual(ColumnBehavior.Basic, createdByUserId.Behavior);
            Assert.AreEqual(SqlOperation.Update, createdByUserId.IgnoreOperations);

            var createdDateUtc = clientMap[(accessUsingInterface ? typeof(ICreateFields) : typeof(Client)).GetProperty(nameof(Client.CreatedDateUtc))];

            Assert.AreEqual("CreatedDateUtc", createdDateUtc.ColumnName);
            Assert.AreEqual(ColumnBehavior.Generated, createdDateUtc.Behavior);
            Assert.AreEqual(SqlOperation.Insert | SqlOperation.Update, createdDateUtc.IgnoreOperations);

            var modifiedByUserId = clientMap[(accessUsingInterface ? typeof(IEditFields) : typeof(Client)).GetProperty(nameof(Client.ModifiedByUserId))];

            Assert.AreEqual("ModifiedByUserId", modifiedByUserId.ColumnName);
            Assert.AreEqual(ColumnBehavior.Basic, modifiedByUserId.Behavior);
            Assert.AreEqual((SqlOperation)0, modifiedByUserId.IgnoreOperations);

            var modifiedDateUtc = clientMap[(accessUsingInterface ? typeof(IEditFields) : typeof(Client)).GetProperty(nameof(Client.ModifiedDateUtc))];

            Assert.AreEqual("ModifiedDateUtc", modifiedDateUtc.ColumnName);
            Assert.AreEqual(ColumnBehavior.Generated, modifiedDateUtc.Behavior);
            Assert.AreEqual(SqlOperation.Insert, modifiedDateUtc.IgnoreOperations);
        }
Пример #16
0
        public static int ScanAndSetBorders(ushort x, ushort y, TileType areaType,
                                            ClientMap map)
        {
            ushort w = map.Width, h = map.Height;

            byte borders = 0;

            if (!IsOppositeTile(x, y, w, h, areaType, map))
            {
                if (IsOppositeTile(x - 1, y, w, h, areaType, map))
                {
                    borders |= 2;
                }
                if (IsOppositeTile(x + 1, y, w, h, areaType, map))
                {
                    borders |= 4;
                }
                if (IsOppositeTile(x, y - 1, w, h, areaType, map))
                {
                    borders |= 8;
                }
                if (IsOppositeTile(x, y + 1, w, h, areaType, map))
                {
                    borders |= 16;
                }
            }

            if (borders == 0)
            {
                borders = 1;
            }

            map.FlagSetBorders(x, y, borders);

            return(borders);
        }
Пример #17
0
        public void Execute(HttpRequest httpRequest, JsonPacket jsonRequest, SessionComponent session)
        {
            // Connect
            NetworkChannel channel = new NetworkChannel(Connection);

            // Request
            JsonJoinRequestMessage jsonRequestMessage = JsonJoinRequestMessage.Parse(jsonRequest.Message);

            // Data
            JsonEntity jsonEntity = jsonRequestMessage.Entity;
            Entity     entity     = EntityMap.Get(jsonEntity.Id);

            if (entity != null)
            {
                entity.Shutdown();
            }

            entity    = session.Owner;
            entity.Id = jsonEntity.Id;
            EntityMap.Add(entity.Id, entity);
            Server.Entities = EntityMap.Count;

            JsonGroup jsonGroup = jsonRequestMessage.Group;

            if (jsonGroup == null)
            {
                jsonGroup = JsonGroup.Default;
            }

            JsonClient      jsonClient = jsonRequestMessage.Client;
            ClientComponent client     = new ClientComponent(jsonClient.Id, jsonClient.Name);

            entity.Add(client);

            ClientMap.Add(client.Id, entity);
            Server.Clients = ClientMap.Count;

            GroupComponent group = new GroupComponent(jsonGroup.Id);

            entity.Add(group);

            GroupList.Add(group.Id, entity);
            Server.Groups = GroupList.Count;

            SearchListComponent download = new SearchListComponent();

            entity.Add(download);

            // Response
            JsonJoinResponseMessage jsonResponseMessage = new JsonJoinResponseMessage()
            {
                Entities = Server.Entities, Sessions = Server.Sessions, Clients = Server.Clients, Groups = Server.Groups
            };
            JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage);

            HttpResponse httpResponse = new HttpResponse()
            {
                Data = session.Encrypt(jsonResponse)
            };

            channel.Send(httpResponse);
#if DEBUG
            Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
        }
Пример #18
0
        /// <summary>
        /// 监控设备,巡检指令心跳,增加巡检设备
        /// 间隔超过5分钟自动认为该指令退出
        /// </summary>
        /// <param name="info">指令内容:service='monitor',device,id,patrol='true'(patrol持续执行)</param>
        /// <param name="client">客户端连接信息</param>
        public void Monitordev(NameValueCollection info, ClientInfo client)
        {
            if (null == info || null == client || null == client.Client || !client.Client.Connected)
                return;
            string cmdid = info["id"];
            string devid = info["device"];
            if (string.IsNullOrEmpty(cmdid))
                return;
            ServiceTool.LogMessage("启动巡检:" + cmdid + "\r\n设备:" + devid, null, EventLogEntryType.Warning);
            //增加客户端连接信息
            ClientMap[] cms = this.clientlist.ToArray();
            ClientMap cm = null;
            for (int i = cms.Length - 1; i > -1; i--)
            {
                if (null == cms[i] || null == cms[i].client.Client || !cms[i].client.Client.Connected)
                    continue;
                if (client != cms[i].client)
                    continue;
                cm = cms[i];
                break;
            }
            if (null == cm)
            {
                cm = new ClientMap();
                cm.client = client;
                this.clientlist.Add(cm);
            }
            //添加监听指令
            MonitorCommand cmd = null;
            foreach (MonitorCommand mcd in cm.cmds)
                if (cmdid == mcd.cmdid)
                {
                    cmd = mcd;
                    break;
                }
            if (null == cmd)
            {
                cmd = new MonitorCommand();
                cmd.cmdid = cmdid;
                cm.cmds.Add(cmd);
            }
            cmd.dtbeat = DateTime.Now;

            //增加监听巡检设备
            if (string.IsNullOrEmpty(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            devid = "," + devid + ",";
            devid = devid.Replace(",,", ",");
            if (cmd.devices.Contains(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            //加入设备列表,并增加巡检设备
            if (string.IsNullOrEmpty(cmd.devices))
                cmd.devices = devid;
            else
                cmd.devices += devid.Substring(1);
            bool ispatrol = false;
            if ("true" == info["patrol"])
                ispatrol = true;
            devid = devid.Replace(",", "");
            this.addDevice(devid, ispatrol);
            this.returnInfo(info, client, true);
        }
Пример #19
0
        public void Render(MapControl mapCtrl, Graphics buffer, Rectangle area)
        {
            ClientMap map = mapCtrl.Map;

            if (map == null)
            {
                return;
            }

            float scale     = mapCtrl.ScaleFactor;
            float pixelSize = ConstMap.PIXEL_SIZE * scale;

            ushort mapX1 = (ushort)Math.Max(Math.Floor(mapCtrl.PosX / pixelSize - 1), 0);
            ushort mapY1 = (ushort)Math.Max(Math.Floor(mapCtrl.PosY / pixelSize - 1), 0);
            ushort mapX2 = (ushort)Math.Min(Math.Ceiling(mapCtrl.Width / scale / pixelSize + 2) + mapX1, map.Width);
            ushort mapY2 = (ushort)Math.Min(Math.Ceiling(mapCtrl.Height / scale / pixelSize + 2) + mapY1, map.Height);

            for (ushort y = mapY1; y < mapY2; y++)
            {
                for (ushort x = mapX1; x < mapX2; x++)
                {
                    Tile *tile = map[x, y];
                    if (tile != null && (*tile).Type == TileType.Wall)
                    {
                        float x1 = x * pixelSize - mapCtrl.PosX;
                        float y1 = y * pixelSize - mapCtrl.PosY;

                        int borders = map.Borders(x, y);
                        if (borders == 0)
                        {
                            borders = TileBorders.ScanAndSetBorders(x, y, TileType.Wall, map);
                        }

                        if (borders < 2)
                        {
                            continue;
                        }

                        float x2, y2;
                        if ((borders | 2) == borders)
                        {
                            y2 = y1 + pixelSize - 0;
                            buffer.DrawLine(_borderPen, x1, y1, x1, y2);
                        }
                        if ((borders | 4) == borders)
                        {
                            x2 = x1 + pixelSize - 0;
                            y2 = y1 + pixelSize - 0;
                            buffer.DrawLine(_borderPen, x2, y1, x2, y2);
                        }
                        if ((borders | 8) == borders)
                        {
                            x2 = x1 + pixelSize - 0;
                            buffer.DrawLine(_borderPen, x1, y1, x2, y1);
                        }
                        if ((borders | 16) == borders)
                        {
                            x2 = x1 + pixelSize - 0;
                            y2 = y1 + pixelSize - 0;
                            buffer.DrawLine(_borderPen, x1, y2, x2, y2);
                        }
                    }
                }
            }
        }
        public static (ClientMapTile selectedTile, Vector2 tilePosition) GetHighlightedTile(GameEngine engine, ClientMap map)
        {
            MouseState mouse = Mouse.GetState();

            if (mouse.X < 0 || mouse.Y < 0)
            {
                return(null, new Vector2(-1, -1));
            }

            Vector2 cameraOffset      = engine.Renderer.CameraOffset;
            float   mx                = mouse.X - cameraOffset.X;
            float   my                = mouse.Y - cameraOffset.Y + ClientMapTile.TILE_HEIGHT / 2f;
            Vector2 projectedPosition = new Vector2(mx, my);
            Vector2 result            = ViewPerspectives.ISOMETRIC.ToInternal(projectedPosition);
            float   rx                = result.X - ClientMapTile.TILE_WIDTH;
            float   ry                = result.Y;

            int selectX = (int)(rx / ClientMapTile.TILE_WIDTH);

            if (selectX < 0 || selectX > map.Width - 1)
            {
                return(null, new Vector2(-1, -1));
            }

            int selectY = (int)(ry / ClientMapTile.TILE_HEIGHT);

            if (selectY < 0 || selectY > map.Height - 1)
            {
                return(null, new Vector2(-1, -1));
            }

            int selectIndex = selectX + selectY * map.Width;

            return(map[selectIndex], new Vector2(selectX, selectY));
        }
Пример #21
0
 public UDPServerSocket() : base(Protocols.UDP)
 {
     clients    = new UDPClientList();
     clientsMap = new ClientMap();
 }
Пример #22
0
        public JsonAction Execute(HttpRequest httpRequest, JsonPacket jsonRequest, SessionComponent session)
        {
            Clear();

            // Connect
            NetworkChannel channel = new NetworkChannel(Connection);

            // Request
            JsonAction jsonAction = JsonAction.None;
            JsonDownloadRequestMessage jsonRequestMessage = JsonDownloadRequestMessage.Parse(jsonRequest.Message);
            string jsonId = jsonRequestMessage.Id;

            if (jsonId != null)
            {
                // Data
                Entity entity = TransferMap.Get(jsonId);
                if (entity == null)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                ChunkComponent transfer = entity.Get <ChunkComponent>();
                if (transfer == null)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                JsonTransfer jsonTransfer = transfer.PopData();
                if (!transfer.Finished)
                {
                    jsonAction = JsonAction.Request;
                    entity.Update();
                }
                else
                {
                    TransferMap.Remove(jsonId);
                }

                string    jsonData  = null;
                JsonChunk jsonChunk = null;
                if (jsonTransfer != null)
                {
                    jsonData  = jsonTransfer.Data;
                    jsonChunk = jsonTransfer.Chunk;
                }

                // Response
                JsonDownloadResponseMessage jsonResponseMessage = new JsonDownloadResponseMessage(jsonId)
                {
                    Chunk = jsonChunk
                };
                JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage, jsonData);

                HttpResponse httpResponse = new HttpResponse()
                {
                    Data = session.Encrypt(jsonResponse)
                };
                channel.Send(httpResponse);
#if DEBUG
                jsonResponse.Data = null;
                Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
            }
            else
            {
                // Data
                Entity entity = session.Owner;
                SearchListComponent search     = entity.Get <SearchListComponent>();
                JsonClient          jsonClient = jsonRequestMessage.Client;

                // Request
                if (jsonClient == null && search.Empty)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                // Response
                jsonId = SecurityUtil.CreateKeyString();
                JsonDownloadResponseMessage jsonResponseMessage = new JsonDownloadResponseMessage(jsonId);
                JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage);

                HttpResponse httpResponse = new HttpResponse()
                {
                    Data = session.Encrypt(jsonResponse)
                };
                channel.Send(httpResponse);
#if DEBUG
                Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
                // Data
                entity = new Entity(jsonId);
                EntityIdleComponent idle = new EntityIdleComponent();
                entity.Add(idle);

                JsonChunk      jsonChunk = jsonRequestMessage.Chunk;
                ChunkComponent transfer  = new ChunkComponent(jsonChunk.Size, Options.ChunkSize, Options.MaxChunks);
                entity.Add(transfer);

                TransferMap.Add(entity);

                // Command
                string jsonData = jsonRequest.Data;
                jsonChunk = transfer.PopChunk();

                if (jsonClient == null)
                {
                    foreach (Entity e in search)
                    {
                        CommandState state = new CommandState()
                        {
                            Id = jsonId, Data = jsonData, Chunk = jsonChunk, Entity = e
                        };
                        Thread thread = new Thread(new ParameterizedThreadStart(ExecuteThread))
                        {
                            Priority = ThreadPriority.BelowNormal, IsBackground = true
                        };
                        thread.Start(state);
                    }
                }
                else
                {
                    Entity e = ClientMap.Get(jsonClient.Id);
                    if (e == null)
                    {
                        channel.SendNotFound();
                        return(jsonAction);
                    }

                    CommandState state = new CommandState()
                    {
                        Id = jsonId, Data = jsonData, Chunk = jsonChunk, Entity = e
                    };
                    Thread thread = new Thread(new ParameterizedThreadStart(ExecuteThread))
                    {
                        Priority = ThreadPriority.BelowNormal, IsBackground = true
                    };
                    thread.Start(state);
                }

                jsonAction = JsonAction.Request;
            }

            return(jsonAction);
        }
Пример #23
0
        /// <summary>
        /// 监控设备,巡检指令心跳,增加巡检设备
        /// 间隔超过5分钟自动认为该指令退出
        /// </summary>
        /// <param name="info">指令内容:service='monitor',device,id,patrol='true'(patrol持续执行)</param>
        /// <param name="client">客户端连接信息</param>
        public void Monitordev(NameValueCollection info, ClientInfo client)
        {
            if (null == info || null == client || null == client.Client || !client.Client.Connected)
            {
                return;
            }
            string cmdid = info["id"];
            string devid = info["device"];

            if (string.IsNullOrEmpty(cmdid))
            {
                return;
            }
            ServiceTool.LogMessage("启动巡检:" + cmdid + "\r\n设备:" + devid, null, EventLogEntryType.Warning);
            //增加客户端连接信息
            ClientMap[] cms = this.clientlist.ToArray();
            ClientMap   cm  = null;

            for (int i = cms.Length - 1; i > -1; i--)
            {
                if (null == cms[i] || null == cms[i].client.Client || !cms[i].client.Client.Connected)
                {
                    continue;
                }
                if (client != cms[i].client)
                {
                    continue;
                }
                cm = cms[i];
                break;
            }
            if (null == cm)
            {
                cm        = new ClientMap();
                cm.client = client;
                this.clientlist.Add(cm);
            }
            //添加监听指令
            MonitorCommand cmd = null;

            foreach (MonitorCommand mcd in cm.cmds)
            {
                if (cmdid == mcd.cmdid)
                {
                    cmd = mcd;
                    break;
                }
            }
            if (null == cmd)
            {
                cmd       = new MonitorCommand();
                cmd.cmdid = cmdid;
                cm.cmds.Add(cmd);
            }
            cmd.dtbeat = DateTime.Now;

            //增加监听巡检设备
            if (string.IsNullOrEmpty(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            devid = "," + devid + ",";
            devid = devid.Replace(",,", ",");
            if (cmd.devices.Contains(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            //加入设备列表,并增加巡检设备
            if (string.IsNullOrEmpty(cmd.devices))
            {
                cmd.devices = devid;
            }
            else
            {
                cmd.devices += devid.Substring(1);
            }
            bool ispatrol = false;

            if ("true" == info["patrol"])
            {
                ispatrol = true;
            }
            devid = devid.Replace(",", "");
            this.addDevice(devid, ispatrol);
            this.returnInfo(info, client, true);
        }
        private static Dictionary <int, List <CoreAbstractEntity> > GetEntitiesByTilePosition(ClientMap map)
        {
            var result = new Dictionary <int, List <CoreAbstractEntity> >();

            map.Entities.ForEach(entity =>
            {
                if (!entity.GetType().IsSubclassOf(typeof(CoreAbstractEntity)))
                {
                    return;
                }

                int position = entity.GetGridX() + entity.GetGridY() * map.Width;
                if (!result.ContainsKey(position))
                {
                    result[position] = new List <CoreAbstractEntity>();
                }
                result[position].Add(entity);
            });
            return(result);
        }