示例#1
0
        public static async Task<ToxResponse> sendRequest(Skynet host, ToxRequest req) {

            // if req is not send to local node
            if (host.tox.Id.ToString() != req.toToxId) {
                bool mResStatus = false;
                return await host.sendRequest(new ToxId(req.toToxId), req, out mResStatus);
            }

            string baseUrl = "http://localhost:" + host.httpPort + "/";
            var request = (HttpWebRequest)WebRequest.Create(baseUrl + "api/" + req.url);
            request.Headers.Add("Uuid", req.uuid);
            request.Headers.Add("From-Node-Id", req.fromNodeId);
            request.Headers.Add("From-Tox-Id", req.fromToxId);
            request.Headers.Add("To-Node-Id", req.toNodeId);
            request.Headers.Add("To-Tox-Id", req.toToxId);
            request.Headers.Add("Skynet-Time", req.time + "");
            request.Method = req.method.ToUpper();
            request.ContentType = "application/json";

            List<string> allowedMethods = new List<string> { "POST", "PUT", "PATCH" };
            if (allowedMethods.Any(x => x == req.method.ToUpper())) {
                // only the above methods are allowed to add body data
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(req.content);
                }
            }
            var response = await request.GetResponseAsync();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return req.createResponse(responseString);
        }
示例#2
0
    static void Main(string[] args)
    {
        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int    N       = int.Parse(inputs[0]); // the total number of nodes in the level, including the gateways
        int    L       = int.Parse(inputs[1]); // the number of links
        int    E       = int.Parse(inputs[2]); // the number of exit gateways
        Skynet network = new Skynet(N);

        for (int i = 0; i < L; i++)
        {
            inputs = Console.ReadLine().Split(' ');
            int N1 = int.Parse(inputs[0]); // N1 and N2 defines a link between these nodes
            int N2 = int.Parse(inputs[1]);
            Skynet.CreateLink(N1, N2);
        }
        for (int i = 0; i < E; i++)
        {
            int EI = int.Parse(Console.ReadLine()); // the index of a gateway node
            Skynet.ToGateway(EI);
        }

        // game loop
        while (true)
        {
            int SI = int.Parse(Console.ReadLine()); // The index of the node on which the Skynet agent is positioned this turn
            //Skynet.CalculateDistance(network[SI], 0);
            var link = Skynet.CutLink(SI);
            Console.WriteLine("{0} {1}", link.Item1, link.Item2);
        }
    }
示例#3
0
        public NodeResponse GetAll(string nodeId)
        {
            Skynet host = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();

            // check if a valid nodeid
            if (!Utils.Utils.isValidGuid(nodeId))
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "not a valid nodeid",
                });
            }
            Node targetNode = Node.AllLocalNodes.Where(x => x.selfNode.uuid == nodeId).DefaultIfEmpty(null).FirstOrDefault();

            if (targetNode == null)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.NotFound,
                    description = "target node can not be found on the client",
                });
            }
            return(new NodeResponse {
                statusCode = NodeResponseCode.OK,
                description = "success",
                value = JsonConvert.SerializeObject(targetNode.brotherNodes),
                time = targetNode.brotherModifiedTime,
            });
        }
    static void Main(string[] args)
    {
        string[] inputs = Console.ReadLine().Split(' ');
        //Console.Error.WriteLine(string.Join(" ", inputs));
        int    N     = int.Parse(inputs[0]); // the total number of nodes in the level, including the gateways
        int    L     = int.Parse(inputs[1]); // the number of links
        int    E     = int.Parse(inputs[2]); // the number of exit gateways
        Skynet nodes = new Skynet(N);

        for (int i = 0; i < L; i++)
        {
            inputs = Console.ReadLine().Split(' ');
            int N1 = int.Parse(inputs[0]); // N1 and N2 defines a link between these nodes
            int N2 = int.Parse(inputs[1]);
            nodes.CreateLink(nodes[N1], nodes[N2]);
        }
        for (int i = 0; i < E; i++)
        {
            int EI = int.Parse(Console.ReadLine()); // the index of a gateway node
            nodes.ToGateway(nodes[EI]);
        }
        while (true)
        {
            int SI = int.Parse(Console.ReadLine()); // The index of the node on which the Skynet agent is positioned this turn
            Tuple <Skynet.Node, Skynet.Node> link = nodes.SeverLink(SI);
            Console.WriteLine("{0} {1}", link.Item1.Val, link.Item2.Val);
        }
    }
示例#5
0
    IEnumerator test()
    {
        var actor = Skynet.ActorOf(echo);
        var ask1  = actor.Ask(1);

        yield return(ask1);

        ask1.Then(value => Debug.Log(value));
    }
示例#6
0
        public NodeResponse Post([FromBody] List <NodeId> parents)
        {
            Skynet mSkynet = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();
            Node   newNode = new Node(parents, mSkynet);

            return(new NodeResponse {
                statusCode = NodeResponseCode.OK,
                description = "success",
                value = JsonConvert.SerializeObject(newNode.getInfo()),
            });
        }
示例#7
0
        public NodeResponse GetAll()
        {
            Skynet        mSkynet  = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();
            List <NodeId> nodeList = Node.AllLocalNodes.Where(x => x.mSkynet.httpPort == mSkynet.httpPort)
                                     .Select(x => x.selfNode).ToList();

            return(new NodeResponse {
                statusCode = NodeResponseCode.OK,
                description = "success",
                value = JsonConvert.SerializeObject(nodeList)
            });
        }
示例#8
0
        public void GetsBackT800Model()
        {
            // Arrange | Act
            var t800 = Skynet.MakeT800();

            // Assert
            Equal("Keep alive", t800.Mission());
            Equal("Come with me if you want to live", t800.Talk());
            Equal(75, t800.Legs.Power());
            Equal(200, t800.Head.Power());
            Equal(100, t800.Torso.Power());
            Equal(150, t800.Arms.Power());
            Empty(t800.Extras);
        }
示例#9
0
        public void GetsBackTxModel()
        {
            // Arrange | Act
            var tx = Skynet.MakeTx();

            // Assert
            Equal("Kill", tx.Mission());
            Equal("Kill Sarah Conor", tx.Talk());
            Equal(75, tx.Legs.Power());
            Equal(200, tx.Head.Power());
            Equal(500, tx.Torso.Power());
            Equal(150, tx.Arms.Power());
            Single(tx.Extras);
            Equal(50, tx.Extras.First().Power());
            Equal(300, ((WeaponPart)tx.Extras.First()).Damage());
        }
示例#10
0
        public async Task <NodeResponse> Get(string id)
        {
            Skynet curHost = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();

            if (!ToxId.IsValid(id))
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "your tox id is invalid",
                });
            }

            // check if target tox client is local client
            if (curHost.tox.Id.ToString() == id)
            {
                // list all nodes on target tox client
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.OK,
                    description = "success",
                    value = JsonConvert.SerializeObject(new ToxClient
                    {
                        Id = id,
                        nodes = Node.AllLocalNodes.Select(x => x.getInfo()).ToList()
                    })
                });
            }
            // if not, send tox req to target tox client
            bool        reqStatus    = false;
            ToxResponse nodeResponse = await curHost.sendRequest(new ToxId(id), RequestProxy.toNodeRequest(Request), out reqStatus);

            if (nodeResponse != null)
            {
                return(JsonConvert.DeserializeObject <NodeResponse>(Encoding.UTF8.GetString(nodeResponse.content)));
            }
            else
            {
                return new NodeResponse
                       {
                           statusCode  = NodeResponseCode.NotFound,
                           description = "target does not exist or target is current offline",
                       }
            };
        }
示例#11
0
        static void Main(string[] args)
        {
            Action <object> writeLine = Console.WriteLine;
            Func <string>   readLine  = Console.ReadLine;

            var inputs = readLine().Split(' ');

            var N = int.Parse(inputs[0]);
            var L = int.Parse(inputs[1]);
            var G = int.Parse(inputs[2]);

            var graph = Enumerable.Range(0, N).ToDictionary(i => i, i => new Node(i));

            // Add links on nodes
            for (var i = 0; i < L; i++)
            {
                inputs = readLine().Split(' ');
                var from = int.Parse(inputs[0]);
                var to   = int.Parse(inputs[1]);
                graph[from].Childs.Add(to);
                graph[to].Childs.Add(from);
            }

            // Set gateway
            for (var i = 0; i < G; i++)
            {
                graph[int.Parse(readLine())].SetAsGateway();
            }

            var skynet = new Skynet(graph);

            while (true)
            {
                writeLine(skynet.Move(int.Parse(readLine())));
            }
        }
示例#12
0
        public NodeResponse Put(string nodeId, [FromBody] NodeId values)
        {
            IEnumerable <string> requestTime = new List <string>();

            if (!Request.Headers.TryGetValues("Skynet-Time", out requestTime))
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "you need to add some http headers"
                });
            }

            if (!Utils.Utils.isValidGuid(nodeId))
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "your node id is invalid",
                });
            }
            Node targetNode = Node.AllLocalNodes.Where(x => x.selfNode.uuid == nodeId).DefaultIfEmpty(null).FirstOrDefault();

            if (targetNode == null)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.NotFound,
                    description = "target node cannot be found on the client",
                });
            }
            // check lock
            if (targetNode.nodeChangeLock.isLocked == true)
            {
                // target is locked, cannot be changed at this time
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.TargetLocked,
                    description = "target is locked",
                });
            }
            else
            {
                long reqTime = long.Parse(requestTime.DefaultIfEmpty("0").FirstOrDefault());
                if (reqTime < targetNode.brotherModifiedTime)
                {
                    return(new NodeResponse
                    {
                        statusCode = NodeResponseCode.OutOfDate,
                        description = "Your data is outofdate",
                    });
                }
                targetNode.parentModifiedTime = reqTime;
                targetNode.parent             = values;

                Task.Run(async() =>
                {
                    // get parent node info, set grandparents
                    Skynet host = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();
                    bool status = false;
                    ToxResponse getParentInfo = await host.sendRequest(new ToxId(values.toxid), new ToxRequest
                    {
                        url        = "node/" + values.uuid,
                        method     = "get",
                        content    = null,
                        fromNodeId = targetNode.selfNode.uuid,
                        fromToxId  = targetNode.selfNode.toxid,
                        toNodeId   = values.uuid,
                        toToxId    = values.toxid,
                        time       = Utils.Utils.UnixTimeNow(),
                        uuid       = Guid.NewGuid().ToString()
                    }, out status);
                    NodeResponse getParentInfoRes       = JsonConvert.DeserializeObject <NodeResponse>(Encoding.UTF8.GetString(getParentInfo.content));
                    NodeInfo parentInfo                 = JsonConvert.DeserializeObject <NodeInfo>(getParentInfoRes.value);
                    targetNode.grandParents             = parentInfo.parent;
                    targetNode.grandParentsModifiedTime = parentInfo.parentModifiedTime;
                    await BoardCastChanges(targetNode);
                });

                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.OK,
                    description = "set parent success",
                    value = JsonConvert.SerializeObject(values),
                    time = reqTime,
                });
            }
        }
示例#13
0
 void Awake()
 {
     Skynet.ServiceOf(this, "Test2ss1");
 }
示例#14
0
        public NodeResponse Post(string nodeId, [FromBody] NodeId newBrother)
        {
            IEnumerable <string> headerValues = new List <string>();
            IEnumerable <string> requestTime  = new List <string>();

            if (!Request.Headers.TryGetValues("From-Node-Id", out headerValues) ||
                !Request.Headers.TryGetValues("Skynet-Time", out requestTime))
            {
                // can not found from headers
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "you need to add some http headers"
                });
            }
            Skynet host = Skynet.allInstance.Where(x => x.httpPort == Request.RequestUri.Port).FirstOrDefault();

            // check if a valid nodeid
            if (!Utils.Utils.isValidGuid(nodeId))
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.InvalidRequest,
                    description = "not a valid nodeid",
                });
            }
            Node targetNode = Node.AllLocalNodes.Where(x => x.selfNode.uuid == nodeId).DefaultIfEmpty(null).FirstOrDefault();

            if (targetNode == null)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.NotFound,
                    description = "target node can not be found on the client",
                });
            }

            if (targetNode.parent == null || headerValues.FirstOrDefault() != targetNode.parent.uuid)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.NoPermission,
                    description = "you do not have permission to access change brother node",
                });
            }

            if (targetNode.brotherNodes.Count >= 10)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.TargetIsFull,
                    description = "target brother nodes is full"
                });
            }

            if (targetNode.brotherNodes.Where(x => x.uuid == newBrother.uuid).Count() != 0)
            {
                return new NodeResponse
                       {
                           statusCode  = NodeResponseCode.AlreadyExist,
                           description = "target already existed"
                       }
            }
            ;

            if (targetNode.nodeChangeLock.isLocked)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.TargetLocked,
                    description = "target is locked",
                });
            }

            if (long.Parse(requestTime.DefaultIfEmpty("0").FirstOrDefault())
                < targetNode.brotherModifiedTime)
            {
                return(new NodeResponse
                {
                    statusCode = NodeResponseCode.OutOfDate,
                    description = "Your data is outofdate",
                });
            }

            targetNode.brotherNodes.Add(newBrother);
            return(new NodeResponse {
                statusCode = NodeResponseCode.OK,
                description = "success",
                value = JsonConvert.SerializeObject(targetNode.brotherNodes),
            });
        }