Ejemplo n.º 1
0
        /// <summary>
        /// Add a network node and connects if it hasn't been done already.
        /// Duplicate network nodes cannot exist in the pool.
        /// Maximum of x connected nodes are allowed.
        /// <seealso cref="NetworkConstants.MaxConcurrentConnections"/>
        /// </summary>
        /// <param name="node">The node to add</param>
        public bool AddNetworkNode(NetworkNode node)
        {
            var added = false;

            if (!node.IsDisposed && Count() < NetworkConstants.MaxConcurrentConnections)
            {
                lock (_nodesPool)
                {
                    var endpoint = node.ListenEndpoint ?? node.DirectEndpoint;
                    if (!_nodesPool.Values.Where(
                            n => (n.ListenEndpoint != null && n.ListenEndpoint.Address.ToString().Contains(endpoint.Address.ToString())) ||
                            (n.DirectEndpoint != null && n.DirectEndpoint.Address.ToString().Contains(endpoint.Address.ToString()))).Any())
                    {
                        added = _nodesPool.TryAdd(node.ToString(), node);
                    }
                }
            }

            if (added)
            {
                _logger.LogDebug("Added node {0} to pool. {0}/{1} connections.", node.Id, Count(), NetworkConstants.MaxConcurrentConnections);
                // Subscribe to events
                node.OnDisconnected            += Node_OnDisconnected;
                node.OnListenerEndpointChanged += Node_OnListenerEndpointChanged;
            }

            return(added);
        }
Ejemplo n.º 2
0
        public override async Task HandleMessage(NetworkNode node, Message msg)
        {
            if (node.HandshakeIsCompleted)
            {
                return;
            }

            var blockchain = _blockchainRepo.GetChainByNetId(_netId);

            try
            {
                if (node.ConnectionType == ConnectionType.Inbound)
                {
                    await HandleInboundHandshakeMessage(node, msg, blockchain);
                }
                else
                {
                    await HandleOutboundHandshakeMessage(node, msg, blockchain);
                }
            }
            catch (Exception)
            {
                node?.Disconnect();
            }
        }
Ejemplo n.º 3
0
        public async Task <bool> AddAsync(string enode, bool updateFile = true)
        {
            NetworkNode node = new NetworkNode(enode);

            if (!_nodes.TryAdd(node.NodeId, node))
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Static node was already added: {enode}");
                }
                return(false);
            }

            if (_logger.IsInfo)
            {
                _logger.Info($"Static node added: {enode}");
            }
            NodeAdded?.Invoke(this, new NetworkNodeEventArgs(node));
            if (updateFile)
            {
                await SaveFileAsync();
            }

            return(true);
        }
Ejemplo n.º 4
0
        public void Render(NetworkNode node, RenderWindow win, CharacterEntity character, View charView)
        {
            _win  = win;
            _node = node;
            if (Character != character)
            {
                Reset();
            }
            Character = character;

            GUI.RestoreView = charView;
            GUI.Win         = _win;
            if (character != null)
            {
                GUI.Begin();
                GUI.IsActive = true;
                DrawStats(character);
                //DrawQuests(character as IQuester);
                SelectedInteractive = DrawInteractions(character);
                DrawItems(character, SelectedInteractive);
                GUI.End();
                DrawOverlayForInteractive(SelectedInteractive);

                DrawCurrentSpell(character);
            }
        }
Ejemplo n.º 5
0
        public void CircleInsideRectPolygon()
        {
            Point       pointA = new Point(10, 10);
            NetworkNode nodeA  = new NetworkNode("A", 5, pointA, Color.Red);

            Point       pointB = new Point(40, 10);
            NetworkNode nodeB  = new NetworkNode("B", 5, pointB, Color.Red);

            Link link = new Link(6, nodeA, nodeB, Color.Red);

            bool   collision;
            Point  point;
            Entity entity;

            point     = new Point(20, 10);
            entity    = new Entity(point, Color.Blue);
            collision = link.DetectCollision(entity);
            Assert.IsTrue(collision == false);

            point     = new Point(20, 11);
            entity    = new Entity(point, Color.Blue);
            collision = link.DetectCollision(entity);
            Assert.IsTrue(collision == true);

            point     = new Point(16, 10);
            entity    = new Entity(point, Color.Blue);
            collision = link.DetectCollision(entity);
            Assert.IsTrue(collision == true);
        }
 public Edge(NetworkNode N1, NetworkNode N2, bool[] slots, int len)
 {
     NodeA      = N1;
     NobeB      = N2;
     this.slots = slots;
     length     = len;
 }
Ejemplo n.º 7
0
 public bool testCompatibility(NetworkNode testNode)
 {
     if (this.nodeName == null || testNode.getNodeName() == null)
     {
         return(false);
     }
     if (this.nodeName == "router" && testNode.getNodeName() == "router")
     {
         return(false);
     }
     else if (this.nodeName == "router" || testNode.getNodeName() == "router")
     {
         return(true);
     }
     else if (this.nodeName == "switch" || testNode.getNodeName() == "switch")
     {
         return(true);
     }
     else if (this.nodeName == "accesspoint" || testNode.getNodeName() == "accesspoint")
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 8
0
        /// <param name="component1"></param>
        /// <param name="component2"></param>
        /// <param name="text"></param>
        public void SetLineMessage(NetworkNode component1, NetworkNode component2, string text)
        {
            DiagramAnalysisNodeMessage messageNode;

            //flag node and put up the message
            //if the message is already there over write with the latest edition
            if (dictionaryNodeMessages.ContainsKey(component2.ComponentGuid))
            {
                messageNode = dictionaryNodeMessages[component2.ComponentGuid];
            }
            else if (dictionaryNodeMessages.ContainsKey(component1.ComponentGuid))
            {
                messageNode = dictionaryNodeMessages[component1.ComponentGuid];
            }
            else
            {
                messageNode = new DiagramAnalysisNodeMessage()
                {
                    Component   = (NetworkComponent)component1,
                    NodeId1     = component1.ID,
                    NodeId2     = component2.ID,
                    SetMessages = new HashSet <string>()
                };
                dictionaryNodeMessages.Add(component1.ComponentGuid, messageNode);
                IsMessageAdded = true;
            }
            messageNode.AddMessage(text);
        }
Ejemplo n.º 9
0
    public void Tap(Vector2 position)
    {
        Ray ray = mainCamera.ScreenPointToRay(position);

        PointerEventData ped = new PointerEventData(null);

        ped.position = position;
        List <RaycastResult> results = new List <RaycastResult>();

        EventSystem.current.RaycastAll(ped, results);

        if (results.Count > 0)
        {
            return; // ignorar caso o nó esteja atras de um painel do HUD
        }
        RaycastHit[] hits = Physics.RaycastAll(ray);
        foreach (RaycastHit hit in hits)
        {
            GameObject  go = hit.collider.gameObject;
            NetworkNode nn = go.GetComponent <NetworkNode>();
            if (nn != null)
            {
                GameManager.SetSelectedNode(nn);
            }

            // o nó deve ser a primeira selecao - ignorar hud
            //hit.collider.gameObject.transform.position += new Vector3(0, 5, 0);
        }
    }
Ejemplo n.º 10
0
Archivo: cd.cs Proyecto: Streus/HAK
        public override string execute(params string[] args)
        {
            NetworkNode node = GameManager.currentHost;

            if (!(node is IFileSystem))
            {
                throw new ExecutionException("The current node does not support a file system.");
            }
            FileSystem currentFileSystem = (node as IFileSystem).fileSystem;

            string currentPath = GameManager.currentPath;
            string filename    = args [1];
            File   newFile     = currentFileSystem.getFile(currentPath + "/" + filename);

            if (newFile == null)
            {
                throw new ExecutionException("Directory \"" + filename + "\" does not exist.");
            }

            /*
             * if (!newFile.isDirectory) {
             *      throw new ExecutionException ("Can't change directory into a non-directory file.");
             * }
             */

            // This forces a simplification of paths, so things like "/test/../test/.." get turned into "/".
            GameManager.currentPath = newFile.getPath();
            return("Current directory is now \"" + GameManager.currentPath + "/\".");
        }
Ejemplo n.º 11
0
        private bool registerExistingNode(RegisterMessage message, Socket socket)
        {
            NetworkNode node = new NetworkNode(message.Type, message.Id, (uint)systemTracker.Timeout, message.ParallelThreads, message.SolvableProblems,
                                               clientTracker.BackupServers);

            IPAddress address = (socket.RemoteEndPoint as IPEndPoint).Address;
            int       port    = (ushort)Server.PRIMARY_PORT;

            // TODO hack
            if (clientTracker.BackupServers.Length == 1)
            {
                port = (ushort)Server.PRIMARY_PORT2;
            }

            node.Address = address;
            node.Port    = (ushort)port;

            // Dont inform backup about it self
            // It comes naturally in NoOperation message
            if (node.Type == RegisterType.CommunicationServer &&
                (server.Address.ToString().Equals(address.ToString()) && server.Port == port))
            {
                return(false);
            }

            SmartConsole.PrintLine("Backup adding existing node", SmartConsole.DebugLevel.Advanced);
            clientTracker.AddNode(node);
            return(true);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// function updating status of each thread
 /// </summary>
 /// <param name="node"></param>
 /// <param name="message"></param>
 private void UpdateThreadsStatus(NetworkNode node, StatusMessage message)
 {
     for (int i = 0; i < node.TaskThreads.Count(); i++)
     {
         node.TaskThreads[i].StatusThread.State = message.Threads[i].State;
     }
 }
        /// <summary>
        /// Helper method that catches new messages (and handles connection exceptions).
        /// When an exception occurs, we will disconnect with the peer.
        /// </summary>
        /// <param name="node">The node to listen to</param>
        /// <param name="timeout">The message timeout to maintain. Disconnect when timeout has been exceeded.</param>
        /// <returns>The message that we received from the node</returns>
        public async Task <Message> ListenForNewMessage(NetworkNode node, TimeSpan timeout)
        {
            try
            {
                var msg = await node.ReceiveMessageAsync(timeout);

                /*
                 * var delaySec = 0;
                 * Random rnd = new Random();
                 * int delayChance = rnd.Next(1, 100);
                 * if (delayChance > 55 && delayChance < 86)
                 * {
                 *  delaySec = rnd.Next(1, 3);
                 * }
                 * else if (delayChance > 85 && delayChance < 96)
                 * {
                 *  delaySec = rnd.Next(3, 6);
                 * }
                 * else if (delayChance > 95 && delayChance < 101)
                 * {
                 *  delaySec = rnd.Next(7, 13);
                 * }
                 *
                 * await Task.Delay(delaySec * 1000);
                 */
                return(msg);
            }
            catch (Exception)
            {
                await node?.Disconnect();
            }

            return(null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// this function is a response to task manager status message
        /// </summary>
        /// <param name="networkNode"></param>
        /// <param name="messagePackage"></param>
        private void ReactToTaskManagerStatusMessage(NetworkNode networkNode, MessagePackage messagePackage)
        {
            //checks if divide or merge solution message has been sent. If not than send noOperation message.
            bool hasMessageBeenSent       = false;
            int  numberOfAvaliableThreads = AvaliableThreadsCount(networkNode);

            for (int i = 0; i < taskTracker.Tasks.Count && numberOfAvaliableThreads > 0; i++)
            {
                if (isMessageProblemDividedSent(i, networkNode, messagePackage))
                {
                    hasMessageBeenSent = true;
                    numberOfAvaliableThreads--;
                }
            }
            // If there are avaliable threads than try to send merge solution message
            for (int i = 0; i < taskTracker.Tasks.Count && numberOfAvaliableThreads > 0; i++)
            {
                if (isMergeSolutionSent(i, networkNode, messagePackage))
                {
                    hasMessageBeenSent = true;
                    numberOfAvaliableThreads--;
                }
            }

            //if divideProblemMessage hasn't been sent than send noOperationMessage
            if (hasMessageBeenSent == false && Server.primaryMode)
            {
                NoOperationMessage response = new NoOperationMessage(clientTracker.BackupServers);
                server.Send(messagePackage.Socket, response);

                SmartConsole.PrintLine("Sent a NoOperation Message. 0 tasks to divide or 0 apropriate task managers", SmartConsole.DebugLevel.Basic);
            }
        }
Ejemplo n.º 15
0
        /******************************************************************/
        /************************** CONSTRUCTORS **************************/
        /******************************************************************/

        public MessageProcessor(ClientMessageHandler messageHandler, NetworkClient client, NetworkNode node)
        {
            this.client         = client;
            this.messageHandler = messageHandler;

            this.node = node;
        }
Ejemplo n.º 16
0
        public async Task <bool> RemoveAsync(string enode, bool updateFile = true)
        {
            var node    = new NetworkNode(enode);
            var removed = _nodes.TryRemove(node.NodeId, out _);

            if (!removed && _logger.IsDebug)
            {
                _logger.Debug($"Static node already was not found: {enode}");
            }
            else
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Static node was removed: {enode}");
                }
                if (updateFile)
                {
                    await SaveFileAsync();
                }
            }

            var args = new RemoveNetworkNodeEventArgs(node, removed);

            NodeRemoved?.Invoke(this, args);
            return(args.Removed);
        }
Ejemplo n.º 17
0
 public long ping(NetworkNode node)
 {
     return(pingRecur(node.ip, new Dictionary <NetworkNode, int>()
     {
         { this, 0 }
     }));
 }
Ejemplo n.º 18
0
        public async Task <bool> RemoveAsync(string enode, bool updateFile = true)
        {
            NetworkNode node = new NetworkNode(enode);

            if (!_nodes.TryRemove(node.NodeId, out _))
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Static node was not found: {enode}");
                }
                return(false);
            }

            if (_logger.IsInfo)
            {
                _logger.Info($"Static node was removed: {enode}");
            }
            NodeRemoved?.Invoke(this, new NetworkNodeEventArgs(node));
            if (updateFile)
            {
                await SaveFileAsync();
            }

            return(true);
        }
Ejemplo n.º 19
0
    // Use this for initialization
    void Start()
    {
        //TODO: Make this into a Network object, and serialize it into a level.

        /*
         * RouterNode route1 = new RouterNode ("test1", "1");
         * RouterNode route2 = new RouterNode ("test2", "2");
         *
         * DesktopNode desk1 = new DesktopNode ("George's computer", "1.1");
         * DesktopNode desk2 = new DesktopNode ("George's server", "1.2");
         * desk2.active = false;
         *
         * DesktopNode desk3 = new DesktopNode ("Remote server", "2.1");
         *
         * route1.addConnection(route2);
         * desk1.addConnection (route1);
         * desk2.addConnection (route1);
         * desk3.addConnection (route2);
         *
         * currentHost = desk1;
         */

        currentLevel = Network.getLevel1();
        currentHost  = currentLevel.getStart();
    }
Ejemplo n.º 20
0
    private IEnumerator DoTakeOver(NetworkNode nn)
    {
        Debug.Log("STARTED TRACE COROUTINE");
        foreach (var conn in nn.Connetions)
        {
            int otherNodeIndex = (conn.nodes[0].netnode == nn) ? 1 : 0;
            if (conn.nodes[otherNodeIndex].netnode.CapFirewall >= 100)
            {
                conn.Trigger(1, otherNodeIndex);
            }
        }

        yield return(new WaitForSeconds(Connection.LineDrawGroup.movetime));

        Factory.Singleton.SpawnActionTag(nn.gameObject, actionTag.ATOwner.OwnerEnemy, actionTag.ATTrackProperty.TrackCapture);
        float capf         = 1f;
        float startime     = Time.time;
        float expectedTime = GetFirewallTime(nn);

        while (nn.CapFirewall < 100)
        {
            if (bModoStop)
            {
                yield return(new WaitUntil(() => bModoStop == false));
            }
            float totalTime = GetFirewallTime(nn);

            capf          += 99f * Time.deltaTime / totalTime;
            nn.CapFirewall = Mathf.CeilToInt(capf);
            yield return(new WaitForEndOfFrame());
        }
        Debug.Log(string.Format("TRACE COMPLETE {5}: {0} of expected {1} [FBT:{2} CP:{3} FORT:{4}]", (Time.time - startime), expectedTime, firewallBaseTime, nn.CapPlayer, nn.Fortification, nn.Type));
        audioEffects.playSprite(audioEffects.effectType.firewallcap);
        PropagateFirewall(nn);
    }
Ejemplo n.º 21
0
        private async Task HandleInboundHandshakeMessage(NetworkNode node, Message msg, Blockchain blockchain)
        {
            if (node.HandshakeStage == 0)
            {
                // Receive a version message
                // Verify if the protocol version is the same as ours and set the ListenPort
                var payload = (VersionPayload)msg.Payload;
                if (payload.ProtocolVersion != BlockchainConstants.ProtocolVersion)
                {
                    throw new ArgumentException("Mismatch in protocol version"); // todo maybe create a 'NodeException' or something
                }
                _logger.LogDebug("Accepted version from node {0} on direct port {1}. Remote listen port = {2}", node.DirectEndpoint.Address.ToString(), node.DirectEndpoint.Port, payload.ListenPort);

                node.IsSyncCandidate = payload.BlockHeight > blockchain.CurrentHeight;
                node.SetListenEndpoint(new IPEndPoint(node.DirectEndpoint.Address, payload.ListenPort));

                node.ProgressHandshakeStage();

                // Send an acknowledgement
                await SendMessageToNode(node, NetworkCommand.VerAck, null);

                // Send a version
                ISerializableComponent versionPayload = new VersionPayload(BlockchainConstants.ProtocolVersion, blockchain.CurrentHeight, _networkManager.ListeningPort);
                await SendMessageToNode(node, NetworkCommand.Version, versionPayload);
            }
            else if (node.HandshakeStage == 1 && msg.Command == NetworkCommand.VerAck.ToString())
            {
                // And receive a version acknowledgement
                _logger.LogInformation("Successfully connected to node {0} on port {1}", node.DirectEndpoint.Address.ToString(), node.DirectEndpoint.Port);
                node.ProgressHandshakeStage();

                // Download their transaction pool
                await SendMessageToNode(node, NetworkCommand.GetTxPool, null);
            }
        }
Ejemplo n.º 22
0
    private bool CaptureAction()
    {
        NetworkNode nn = selectedNode;

        if (!CanCapture(nn))
        {
            return(false);
        }

        int numberOfConnections = 0;

        //Debug.Log("NN has " + nn.Connetions.Count);
        foreach (var conn in nn.Connetions)
        {
            int otherNodeIndex = (conn.nodes[0].netnode == nn) ? 1 : 0;
            if (conn.nodes[otherNodeIndex].netnode.CapPlayer >= 100)
            {
                conn.Trigger(0, otherNodeIndex);
                numberOfConnections++;
            }
        }

        audioEffects.playSprite(audioEffects.effectType.connect);

        nn.CapPlayer = 2;
        float captureTime = GetCaptureTime(nn, numberOfConnections);

        StartCoroutine(PerformCapture(nn, DetermineDetection(nn), captureTime, Connection.LineDrawGroup.movetime));

        SetStress();
        return(true);
    }
Ejemplo n.º 23
0
        public bool LoadNodes()
        {
            //Try to load Nodes from disk
            if (File.Exists(NodesFileName))
            {
                _logger.LogInformation($"Loading network nodes from file {NodesFileName}:");
                var theNodesFile = File.ReadAllBytes(NodesFileName);
                NetworkNodes = (List <NetworkNode>)Utility.ByteArrayToObject(theNodesFile);
                int index = 1;
                foreach (var node in NetworkNodes)
                {
                    _logger.LogInformation($"----------Node #{index} -------------------------");
                    _logger.LogInformation($"Access Key:{node.AccessKey}");
                    _logger.LogInformation($"Description:{node.Description}");
                    _logger.LogInformation($"Endpoint:{node.Endpoint}");
                    _logger.LogInformation("--------------------------------------------------");
                    index++;
                }
            }
            else
            {
                _logger.LogWarning("No nodes founds on file, adding myself to nodes");
                NetworkNode myselfNode = new NetworkNode();

                myselfNode.Description = _configuration["NodeIdentification:Name"];
                myselfNode.Endpoint    = _configuration["NodeIdentification:IPEndpoint"];
                AddNode(myselfNode);
            }

            return(true);
        }
Ejemplo n.º 24
0
        public void NetworkNodeSetupTest()
        {
            var networkNodeSerializableParameters = new NetworkNodeModel {
                NetworkAddress          = new NetworkAddress(1),
                NumberOfPorts           = 8,
                CableCloudListeningPort = 10000,
                IpAddress = "127.0.0.1",
                NetworkManagmentSystemListeningPort = 6666,
                SignallingCloudListeningPort        = PortRandomizer.RandomFreePort()
            };

            var serializedParameters = XmlSerializer.Serialize(networkNodeSerializableParameters);

            var args = serializedParameters.Split(' ');

            var joinedArgs = string.Join(" ", args);

            var parameters =
                (NetworkNodeModel)
                XmlSerializer.Deserialize(joinedArgs, typeof(NetworkNodeModel));

            var networkNode = new NetworkNode(parameters);

            networkNode.Initialize();
        }
Ejemplo n.º 25
0
        /******************************************************************/
        /************************** CONSTRUCTORS **************************/
        /******************************************************************/

        public MessageProcessor(ClientMessageHandler messageHandler, NetworkClient client, NetworkNode node)
        {
            this.client = client;
            this.messageHandler = messageHandler;

            this.node = node;
        }
Ejemplo n.º 26
0
        public async Task <byte[]> CallGetDataBlockBytes(int Id, NetworkNode node)
        {
            HttpClient client = new HttpClient();

            byte[] blockBytes = null;
            client.BaseAddress = new Uri(node.Endpoint); //"http://localhost:64195/"
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var url = WebApi.GetDataBlockBytes.Value + $"{Id}";
                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var responseString = await response.Content.ReadAsStringAsync();

                    //Transform JSON to object
                    blockBytes = JsonConvert.DeserializeObject <byte[]>(responseString);
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Cannot call remote Node");
            }
            return(blockBytes);
        }
Ejemplo n.º 27
0
        public override string execute(params string[] args)
        {
            NetworkNode node = GameManager.currentHost;

            if (!(node is IFileSystem))
            {
                throw new ExecutionException("The current node does not support a file system.");
            }
            FileSystem currentFileSystem = (node as IFileSystem).fileSystem;

            Directory currentFile = currentFileSystem.getFile(GameManager.currentPath) as Directory;
            string    filename    = args [1];

            if (!(currentFile is Directory))
            {
                throw new ExecutionException("Invalid state: Current path is not a directory.");
            }

            if (filename == null || (filename.GetType() != typeof(string)))
            {
                throw new ExecutionException("Invalid argument: filename must be a string.");
            }

            try {
                //currentFileSystem.createFile(filename, currentFile);
                currentFileSystem.createFile(currentFile.getPath() + "/" + filename);
                return("Created new file \"" + filename + "\".");
            } catch (InvalidFileException e) {
                throw new ExecutionException("Could not create file. Reason: " + e.Message);
            }
        }
Ejemplo n.º 28
0
        public override void Update(GameTime gameTime)
        {
            NetworkNode oldNode = HoverNode;

            base.Update(gameTime);
            foreach (NetworkNode n in _networkNodes)
            {
                n.Update(gameTime);
            }
            if (HoverNode == null)
            {
                return;
            }
            if (oldNode != HoverNode)
            {
                float wat = (1f - (float)(_rnd.NextDouble()) / 100);
                _nodeHoverSound.Play((Globals.Settings.SoundVolume * Globals.Settings.MasterVolume), wat, 0f);
            }
            if (HoverNode.InfoBox.Rectangle.X + HoverNode.InfoBox.Rectangle.Width >= Game.Window.ClientBounds.Width - 10)
            {
                HoverNode.InfoBox.ChangeLocation(new Point(HoverNode.Rectangle.Location.X - HoverNode.InfoBox.Rectangle.Width - 20, HoverNode.Rectangle.Location.Y));
            }
            while (HoverNode.InfoBox.Rectangle.Y + HoverNode.InfoBox.Rectangle.Height > Rectangle.Y + Rectangle.Height - 2)
            {
                HoverNode.InfoBox.ChangeLocation(new Point(HoverNode.InfoBox.Rectangle.X, HoverNode.InfoBox.Rectangle.Y - 1));
            }
        }
Ejemplo n.º 29
0
        public IClient Create(string name)
        {
            var user = new NetworkUser(name);
            var node = new NetworkNode(name);

            return(_clientInstanceFactory.Create(user, node));
        }
Ejemplo n.º 30
0
        /// <param name="component1"></param>
        /// <param name="component2"></param>
        /// <param name="text"></param>
        public void SetLineMessage(NetworkNode component1, NetworkNode component2, string text)
        {
            DiagramAnalysisNodeMessage messageNode;
            //flag node and put up the message
            //if the message is already there over write with the latest edition
            ComponentPairing pair = (new ComponentPairing()
            {
                Source = component1.ComponentGuid,
                Target = component2.ComponentGuid
            });

            if (dictionaryLineMessages.ContainsKey(pair))
            {
                return;// messageNode = dictionaryNodeMessages[component2.ComponentGuid];
            }

            //
            string appropriateEdgeId = findEdgeId(component1, component2, pair);

            messageNode = new DiagramAnalysisNodeMessage()
            {
                Component   = (NetworkComponent)component1,
                NodeId1     = component1.ID,
                NodeId2     = component2.ID,
                edgeId      = appropriateEdgeId,
                SetMessages = new HashSet <string>()
            };

            dictionaryLineMessages.Add(pair, messageNode);
            IsMessageAdded = true;
            messageNode.AddMessage(text);
        }
Ejemplo n.º 31
0
    void Awake()
    {
        rigid               = GetComponent <Rigidbody2D>();
        visuals             = transform.Find("visuals");
        coll                = visuals.GetComponent <CircleCollider2D>();
        randGenerator       = new System.Random(UnityEngine.Random.Range(0, 9999999));
        vectoredMetaballMat = transform.Find("metaBallVisuals").GetComponent <SpriteRenderer>().material;
        vectoredMetaballMat.SetFloat("_NumBoids", 8);

        node = NetworkNode.node;
        if (node != null && (node is Client || node is Server))
        {
            id = nextID++;

            if (node is Server)
            {
                node.Subscribe <OutgoingNetworkStreamMessage>(this);
            }
            else if (node is Client && boids.Count == 0)
            {
                Debug.Log("DING!");
                subscribedID = id;
                node.Subscribe(this);
            }

            boids[id] = this;
        }
    }
 public void SendToClient(NetworkNode.ConnectedNode connectedNode, string message,
     string data)
 {
     SendDataWriter writer = BeginMessage(connectedNode, transferMessageType);
     writer.Write(message);
     writer.Write(data);
     EndMessage();
 }
        bool ReceiveMessage_TransferMessageToClient( NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            string message = reader.ReadString();
            string data = reader.ReadString();
            if( !reader.Complete() )
                return false;

            if( ReceiveMessage != null )
                ReceiveMessage( this, message, data );

            return true;
        }
        private bool ReceiveMessage_TransferMessageToServer(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string error)
        {
            string message = reader.ReadString();
            string data = reader.ReadString();
            if (!reader.Complete())
                return false;

            if (ReceiveMessage != null)
                ReceiveMessage(this, sender, message, data);

            return true;
        }
    void Start()
    {
        node = NetworkNode.node;
        if (node == null) //if null, no networking, server controls it if there is networking
        {
            mode = NetworkMode.UNKNOWN;
            StartCoroutine(LocalGoalSpawning());
        }
        else if(node is Server)
        {
            mode = NetworkMode.LOCALSERVER;
            StartCoroutine(ServerGoalSpawning());
        }
        else if (node is Client)
        {
            mode = NetworkMode.REMOTECLIENT;
            node.Subscribe(this);
        }
	}
Ejemplo n.º 36
0
        bool ReceiveMessage_TextToClient( NetworkNode.ConnectedNode sender,
			MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage )
        {
            //get data from message
            uint fromUserIdentifier = reader.ReadVariableUInt32();
            string text = reader.ReadString();
            if( !reader.Complete() )
                return false;

            //get user by identifier
            UserManagementClientNetworkService.UserInfo fromUser = userManagementService.GetUser(
                fromUserIdentifier );
            if( fromUser == null )
            {
                //error. no such user.
                return true;
            }

            if( ReceiveText != null )
                ReceiveText( this, fromUser, text );

            return true;
        }
    void Start()
    {
        node = NetworkNode.node;
        if (node == null) //if null, no networking, server controls it if there is networking
        {
            mode = NetworkMode.UNKNOWN;
        }
        else if (node is Server)
        {
            mode = NetworkMode.LOCALSERVER;
            node.Subscribe(this);
        }
        else if (node is Client)
        {
            mode = NetworkMode.REMOTECLIENT;
            node.Subscribe(this);
        }

        for (int i = 0; i < charactersData.Length; i++)
        {
            charactersData[i].characterID = i;
        }
    }
        protected override bool OnIncomingConnectionApproval(NetworkNode.ConnectedNode connectedNode,
            string clientVersion, string loginName, string password, ref string rejectReason)
        {
            if (!base.OnIncomingConnectionApproval(connectedNode, clientVersion, loginName,
                password, ref rejectReason))
                return false;

            if (!AllowToConnectNewClients)
            {
                rejectReason = string.Format(
                    "Game is already begun. Game do not support to connect after start.");
                return false;
            }

            //check login and password
            //(use this code for rejection)
            //if(false)
            //{
            //	rejectReason = "Login failed";
            //	return false;
            //}

            return true;
        }
        private bool ReceiveMessage_TextToServer(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            //get source user
            UserManagementServerNetworkService.UserInfo fromUser = userManagementService.
                GetUser(sender);

            //get data of message
            string text = reader.ReadString();
            uint privateToUserIdentifier = reader.ReadVariableUInt32();
            if (!reader.Complete())
                return false;

            //send text to the clients
            if (privateToUserIdentifier != 0)
            {
                //send text to the specific user

                UserManagementServerNetworkService.UserInfo privateToUser = userManagementService.
                    GetUser(privateToUserIdentifier);
                if (privateToUser != null)
                {
                    SendText(fromUser, text, privateToUser);
                }
                else
                {
                    //no user anymore
                }
            }
            else
            {
                SendText(fromUser, text, null);
            }

            return true;
        }
 public UserInfo GetUser(NetworkNode.ConnectedNode connectedNode)
 {
     UserInfo user;
     if (!usersByConnectedNode.TryGetValue(connectedNode, out user))
         return null;
     return user;
 }
Ejemplo n.º 41
0
		void CustomMessagesService_ReceiveMessage( CustomMessagesServerNetworkService sender,
			NetworkNode.ConnectedNode source, string message, string data )
		{
			//Warning! Messages must be checked by security reasons.
			//Modified client application can send any message with any data.
			
			if( allowCustomClientCommands )
			{
				//load map
				if( message == "Example_MapLoad" )
				{
					string mapName = data;
					MapDestroy( true );
					if( !MapLoad( mapName ) )
						return;
					return;
				}

				//create map object
				if( message == "Example_CreateMapObject" )
				{
					string[] parameters = data.Split( ';' );
					string typeName = parameters[ 0 ];
					Vec3 position = Vec3.Parse( parameters[ 1 ] );
					Quat rotation = Quat.Parse( parameters[ 2 ] );

					if( Map.Instance != null )
					{
						MapObject entity = (MapObject)Entities.Instance.Create( typeName, Map.Instance );
						entity.Position = position;
						entity.Rotation = rotation;
						entity.PostCreate();
					}

					return;
				}
			}

		}
        bool ReceiveMessage_EntitySystemInternal( NetworkNode.ConnectedNode sender,
			MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage )
        {
            if( serverRemoteEntityWorld == null )
            {
                Log.Fatal( "EntitySystemClientNetworkService: ReceiveMessage_EntitySystemInternal: " +
                    "serverRemoteEntityWorld == null." );
            }

            int entitySystemMessageIdentifier = messageType.Identifier - 1;

            return networkingInterface.ReceiveEntitySystemMessage( serverRemoteEntityWorld,
                entitySystemMessageIdentifier, reader, ref additionalErrorMessage );
        }
 public UserInfo CreateClientUser(NetworkNode.ConnectedNode connectedNode)
 {
     return CreateUser(connectedNode.LoginName, connectedNode);
 }
Ejemplo n.º 44
0
        private void addCameraNode()
        {
            Vector3 pos = EditorHelper.Instance.getMousePosInZ(gameScreenPos, 0);

            NetworkNode<CameraData> newNode = new NetworkNode<CameraData>(new CameraData(pos, -1, false), pos + new Vector3(0, 0, 1000));

            CameraManager.Instance.addNode(newNode);

            if (CameraManager.Instance.getNodes().getNodes().Count == 2)
            {
                CameraManager.Instance.setupCamera();
            }
        }
        private bool ReceiveMessage_WorldDestroyToClient(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            bool newMapWillBeLoaded = reader.ReadBoolean();
            if (!reader.Complete())
                return false;

            if (WorldDestroy != null)
                WorldDestroy(this, newMapWillBeLoaded);

            if (EntitySystemWorld.Instance != null && networkingInterface != null)
            {
                if (serverRemoteEntityWorld != null)
                    networkingInterface.DisconnectRemoteEntityWorld(serverRemoteEntityWorld);
            }
            serverRemoteEntityWorld = null;

            return true;
        }
        bool ReceiveMessage_WorldCreateBeginToClient( NetworkNode.ConnectedNode sender,
			MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage )
        {
            string worldTypeName = reader.ReadString();
            string mapVirtualFileName = reader.ReadString();
            if( !reader.Complete() )
                return false;

            bool remoteWorldAlreadyExists = EntitySystemWorld.Instance.RemoteEntityWorlds.Contains(
                serverRemoteEntityWorld );

            if( !remoteWorldAlreadyExists )
            {
                serverRemoteEntityWorld = new RemoteEntityWorld( "Server remote entity world" );
                networkingInterface.ConnectRemoteEntityWorld( serverRemoteEntityWorld );
            }

            WorldType worldType = EntityTypes.Instance.GetByName( worldTypeName ) as WorldType;
            if( worldType == null )
            {
                Log.Fatal( "EntitySystemClientNetworkService: " +
                    "ReceiveMessage_WorldCreateBeginToClient: World type \"{0}\" is not exists.",
                    worldTypeName );
            }

            if( WorldCreateBegin != null )
                WorldCreateBegin( this, worldType, mapVirtualFileName );

            return true;
        }
Ejemplo n.º 47
0
        private void CheckNetworkEdge(
			NetworkEdge networkEdge, Network network,
			NetworkNode startNode, NetworkNode endNode)
        {
            Assert.IsNotNull(networkEdge);

            CheckNetworkObjectId(networkEdge);

            Assert.AreEqual(network, networkEdge.Network);
            Assert.AreEqual(startNode, networkEdge.StartNode);
            Assert.AreEqual(endNode, networkEdge.EndNode);
        }
        private bool ReceiveMessage_RemoveUserToClient(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            //get data from message
            uint identifier = reader.ReadVariableUInt32();
            if (!reader.Complete())
                return false;

            UserInfo user;
            users.TryGetValue(identifier, out user);

            if (user != null)
                RemoveUser(user);

            return true;
        }
        private bool ReceiveMessage_AddUserToClient(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            //get data from message
            uint identifier = reader.ReadVariableUInt32();
            string name = reader.ReadString();
            bool thisUserFlag = reader.ReadBoolean();
            if (!reader.Complete())
                return false;

            AddUser(identifier, name, thisUserFlag);

            return true;
        }
            //

            internal UserInfo(uint identifier, string name, NetworkNode.ConnectedNode connectedNode)
            {
                this.identifier = identifier;
                this.name = name;
                this.connectedNode = connectedNode;
            }
        private bool ReceiveMessage_EntitySystemInternal(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            ClientRemoteEntityWorld fromRemoteEntityWorld = GetRemoteEntityWorld(sender);
            if (fromRemoteEntityWorld == null)
            {
                //no such world already. as example World has been deleted.
                return true;
            }

            //check for messages from old/destroyed world. We can get this situation after changing map.
            if (worldCheckIdentifier != fromRemoteEntityWorld.ReceivedWorldIdentifier)
                return true;

            int entitySystemMessageIdentifier = messageType.Identifier - 1;

            return networkingInterface.ReceiveEntitySystemMessage(fromRemoteEntityWorld,
                entitySystemMessageIdentifier, reader, ref additionalErrorMessage);
        }
        private bool ReceiveMessage_CheckWorldIdentifierToServer(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            int identifier = reader.ReadInt32();
            if (!reader.Complete())
                return false;

            ClientRemoteEntityWorld fromRemoteEntityWorld = GetRemoteEntityWorld(sender);
            if (fromRemoteEntityWorld == null)
            {
                //no such world already. as example World has been deleted.
                return true;
            }

            fromRemoteEntityWorld.ReceivedWorldIdentifier = identifier;

            return true;
        }
Ejemplo n.º 53
0
            void GetConnectedNodeData( NetworkNode.ConnectedNode connectedNode, StringBuilder text )
            {
                if( connectedNode.Status == NetworkConnectionStatuses.Connected )
                {
                    text.AppendFormat( "- Connection with {0}\n", connectedNode.RemoteEndPoint.Address );

                    NetworkNode.ConnectedNode.StatisticsData statistics = connectedNode.Statistics;

                    text.AppendFormat(
                        "-   Send: Total: {0} kb, Speed: {1} b/s\n",
                        statistics.GetBytesSent( true ) / 1024,
                        (long)statistics.GetBytesSentPerSecond( true ) );

                    text.AppendFormat(
                        "-   Receive: Total: {0} kb, Speed: {1} b/s\n",
                        statistics.GetBytesReceived( true ) / 1024,
                        (long)statistics.GetBytesReceivedPerSecond( true ) );

                    text.AppendFormat( "-   Ping: {0} ms\n",
                        (int)( connectedNode.LastRoundtripTime * 1000 ) );
                }
            }
        bool ReceiveMessage_WorldCreateEndToClient( NetworkNode.ConnectedNode sender,
			MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage )
        {
            if( !reader.Complete() )
                return false;

            if( WorldCreateEnd != null )
                WorldCreateEnd( this );

            return true;
        }
        protected override void OnConnectedNodeConnectionStatusChanged(
            NetworkNode.ConnectedNode connectedNode, NetworkConnectionStatuses status, string message)
        {
            base.OnConnectedNodeConnectionStatusChanged( connectedNode, status, message );

            //connected
            if( status == NetworkConnectionStatuses.Connected )
            {
                //add to user management and send events to all clients
                userManagementService.CreateClientUser( connectedNode );
            }

            //disconnected
            if( status == NetworkConnectionStatuses.Disconnected )
            {
                //remove user
                UserManagementServerNetworkService.UserInfo user = userManagementService.GetUser(
                    connectedNode );
                if( user != null )
                    userManagementService.RemoveUser( user );
            }
        }
 ClientRemoteEntityWorld GetRemoteEntityWorld( NetworkNode.ConnectedNode connectedNode )
 {
     for( int n = 0; n < clientRemoteEntityWorlds.Count; n++ )
     {
         ClientRemoteEntityWorld remoteEntityWorld = clientRemoteEntityWorlds[ n ];
         if( remoteEntityWorld.User.ConnectedNode == connectedNode )
             return remoteEntityWorld;
     }
     return null;
 }
Ejemplo n.º 57
0
        private void CheckNetworkNode(
			NetworkNode networkNode, Network network, string name,
			List<NetworkEdge> incomingEdges, List<NetworkEdge> outgoingEdges)
        {
            Assert.IsNotNull(networkNode);

            CheckNetworkObjectId(networkNode);

            Assert.AreEqual(network, networkNode.Network);
            Assert.AreEqual(name, networkNode.Name);

            Assert.AreEqual(incomingEdges.Count, networkNode.IncomingEdges.Count());
            for (int i = 0; i < incomingEdges.Count; i++)
            {
                Assert.AreEqual(incomingEdges[i], networkNode.IncomingEdges.ElementAt(i));
            }

            Assert.AreEqual(outgoingEdges.Count, networkNode.OutgoingEdges.Count());
            for (int i = 0; i < outgoingEdges.Count; i++)
            {
                Assert.AreEqual(outgoingEdges[i], networkNode.OutgoingEdges.ElementAt(i));
            }
        }
        bool ReceiveMessage_EntitySystemInternal( NetworkNode.ConnectedNode sender,
			MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage )
        {
            RemoteEntityWorld fromRemoteEntityWorld = GetRemoteEntityWorld( sender );
            if( fromRemoteEntityWorld == null )
            {
                //no such world already. as example World has been deleted.
                return true;
            }

            int entitySystemMessageIdentifier = messageType.Identifier - 1;

            return networkingInterface.ReceiveEntitySystemMessage( fromRemoteEntityWorld,
                entitySystemMessageIdentifier, reader, ref additionalErrorMessage );
        }
        private UserInfo CreateUser(string name, NetworkNode.ConnectedNode connectedNode)
        {
            uint identifier = GetFreeUserIdentifier();
            UserInfo newUser = new UserInfo(identifier, name, connectedNode);
            usersByIdentifier.Add(identifier, newUser);
            if (newUser.ConnectedNode != null)
                usersByConnectedNode.Add(newUser.ConnectedNode, newUser);

            {
                MessageType messageType = GetMessageType("addUserToClient");

                //send event about new user to the all users
                foreach (UserInfo user in Users)
                {
                    if (user.ConnectedNode != null)
                    {
                        bool thisUserFlag = user == newUser;

                        SendDataWriter writer = BeginMessage(user.ConnectedNode, messageType);
                        writer.WriteVariableUInt32(newUser.Identifier);
                        writer.Write(newUser.Name);
                        writer.Write(thisUserFlag);
                        EndMessage();
                    }
                }

                if (newUser.ConnectedNode != null)
                {
                    //send list of users to new user
                    foreach (UserInfo user in Users)
                    {
                        if (user == newUser)
                            continue;
                        SendDataWriter writer = BeginMessage(newUser.ConnectedNode, messageType);
                        writer.WriteVariableUInt32(user.Identifier);
                        writer.Write(user.Name);
                        writer.Write(false);//this user flag
                        EndMessage();
                    }
                }
            }

            if (AddUserEvent != null)
                AddUserEvent(this, newUser);

            return newUser;
        }
        private bool ReceiveMessage_WorldCreateBeginToClient(NetworkNode.ConnectedNode sender,
            MessageType messageType, ReceiveDataReader reader, ref string additionalErrorMessage)
        {
            string worldTypeName = reader.ReadString();
            string mapVirtualFileName = reader.ReadString();
            int worldCheckIdentifier = reader.ReadInt32();
            if (!reader.Complete())
                return false;

            //send world identifier back to server
            {
                MessageType messageType2 = GetMessageType("worldIdentifierToServer");
                SendDataWriter writer = BeginMessage(messageType2);
                writer.Write(worldCheckIdentifier);
                EndMessage();
            }

            bool remoteWorldAlreadyExists = EntitySystemWorld.Instance.RemoteEntityWorlds.Contains(
                serverRemoteEntityWorld);

            if (!remoteWorldAlreadyExists)
            {
                serverRemoteEntityWorld = new RemoteEntityWorld("Server remote entity world");
                networkingInterface.ConnectRemoteEntityWorld(serverRemoteEntityWorld);
            }

            WorldType worldType = EntityTypes.Instance.GetByName(worldTypeName) as WorldType;
            if (worldType == null)
            {
                Log.Fatal("EntitySystemClientNetworkService: " +
                    "ReceiveMessage_WorldCreateBeginToClient: World type \"{0}\" is not exists.",
                    worldTypeName);
            }

            if (WorldCreateBegin != null)
                WorldCreateBegin(this, worldType, mapVirtualFileName);

            return true;
        }