예제 #1
0
파일: Host.cs 프로젝트: kmc-jp/BounceWars
    void ResponseThread()
    {
        var unprocessedCmds = new Queue <Command>();

        while (!threadAborted)
        {
            //Simulate Lag
            if (simulateLag)
            {
                Thread.Sleep(5);
            }
            ////    Receiving HTTP Request    ////
            //                                  //
            if (_httpListener == null || !_httpListener.IsListening)
            {
                break;
            }

            //Receive HTTP request from client as a stream
            HttpListenerContext context = _httpListener.GetContext();
            StreamReader        reader  = new StreamReader(context.Request.InputStream);
            string resposeFromClient    = reader.ReadToEnd();
            //depack the Json into CommandJsonList object
            CommandJsonList fromClient = JsonUtility.FromJson <CommandJsonList>(resposeFromClient);
            //get the commands inside CommandJsonList
            List <Command> cmds = fromClient.GetCommands();
            //check the type of each command, inside CommandJsonList
            for (int i = 0; i < cmds.Count; i++)
            {
                Command c = cmds[i];
                try
                {
                    //Schin check the classes of Commands
                    switch (c.GetType().ToString())
                    {
                    case "UnitUpdateCmd":
                    case "UnitMovedCmd":
                    case "NewUnitCmd":
                    case "HealingBuffRequestCmd":
                        if (simulator == null)     // simulator is not prepared
                        {
                            unprocessedCmds.Enqueue(c);
                        }
                        else
                        {
                            foreach (var upc in unprocessedCmds)
                            {
                                simulator.commands.Add(upc);
                            }
                            simulator.commands.Add(c);
                        }
                        break;

                    case "UnitTimerCmd":
                        if (((UnitTimerCmd)c).timerType == 2)     // Accept CLIENT LOCKDOWN only
                        {
                            simulator.commands.Add(c);
                        }
                        break;

                    case "LobbyReadyCmd":
                    case "ClientJoinedCmd":
                        interScene.AddCmd(c);
                        break;

                    //case other:
                    //Dump Unknown type Command
                    default:
                        Debug.LogWarning("Unknown Command" + c.GetType());
                        Debug.Log(c);
                        break;
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning(e);
                }
            }

            ////    Responding HTTP Request    ////
            //                                   //
            //create a response JsonList
            CommandJsonList fromHost = new CommandJsonList();

            //collect requests here//
            //collect requests from simulator
            if (simulator != null)
            {
                fromHost.AddRange(simulator.GetCommandsFromHost());
                //collect TimerResetCmd Tinaxd
                fromHost.AddRange(simulator.unitTimerRequests);
                simulator.unitTimerRequests.Clear();
            }
            if (interScene != null)
            {
                List <Command> tst = interScene.GetCmd();
                fromHost.AddRange(tst);
            }

            //after collecting all the responses, convert them into binary stream
            byte[] _responseArray = Encoding.UTF8.GetBytes(JsonUtility.ToJson(fromHost));
            context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length);
            context.Response.Close();


            //Debug.Log("Respone given to a request.");
        }
        Debug.Log("Host thread ended");
    }
예제 #2
0
파일: Client.cs 프로젝트: kmc-jp/BounceWars
    void ResponseThread()
    {
        int timedoutNum     = 0;
        var unprocessedCmds = new Queue <Command>();

        while (!threadAborted)
        {
            //Simulate Lag
            if (simulateLag)
            {
                Thread.Sleep(5);
            }
            ////        Sending HTTP Request        ////
            //                                        //
            // Establish an http request
            string     targetURL = "http://" + interScene.TargetURL + ":5000/";
            WebRequest request   = WebRequest.Create(targetURL);
            request.Timeout = 1000;
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            request.ContentType = "text/json";
            request.Method      = "POST";
            //create a request JsonList
            CommandJsonList fromClient = new CommandJsonList();
            //collect requests here//
            //collect requests from simulator
            if (simulator != null)
            {
                fromClient.AddRange(simulator.commands);
                simulator.SetCommandsSent();
            }
            if (interScene != null)
            {
                fromClient.AddRange(interScene.GetCmd());
            }
            //System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            //timer.Start();
            //after collecting all the requests, convert them into binary stream
            byte[] binary = Encoding.UTF8.GetBytes(JsonUtility.ToJson(fromClient));

            try
            {
                // Send the requests
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(binary, 0, binary.Length);
                }

                ////        receiving HTTP Request        ////
                //                                          //
                // Get the stream containing content returned by the server.
                using (WebResponse response = request.GetResponse())
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        StreamReader reader             = new StreamReader(dataStream);
                        string       responseFromServer = reader.ReadToEnd();
                        //depack the Json into CommandJsonList object
                        CommandJsonList fromHost = JsonUtility.FromJson <CommandJsonList>(responseFromServer);
                        // If the response Json is empty, there's a big chance the host is down.
                        if (fromHost != null)
                        {
                            //get the commands inside CommandJsonList
                            List <Command> cmds = fromHost.GetCommands();
                            for (int i = 0; i < cmds.Count; i++)
                            {
                                Command c = cmds[i];
                                try
                                {
                                    //Schin check the classes of Commands
                                    switch (c.GetType().ToString())
                                    {
                                    case "UnitUpdateCmd":
                                    case "UnitTimerCmd":
                                    case "GameSetCmd":
                                        if (simulator == null) // simulator is not prepared
                                        {
                                            unprocessedCmds.Enqueue(c);
                                        }
                                        else
                                        {
                                            foreach (var upc in unprocessedCmds)
                                            {
                                                simulator.commands.Add(upc);
                                            }
                                            simulator.commands.Add(c);
                                        }
                                        break;

                                    case "LobbyReadyCmd":
                                    case "LobbyStartgameCmd":
                                        interScene.AddCmd(c);
                                        break;

                                    //case other:
                                    //Dump Unknown type Command
                                    default:
                                        Debug.LogWarning("Unknown Command" + c.GetType());
                                        Debug.Log(c);
                                        break;
                                    }
                                    //Debug
                                    //timer.Stop();
                                    //simulator.commands.AddRange()
                                    //simulator.units = data.units;
                                    //simulator.time = data.time + timer.ElapsedMilliseconds * 0.001f * 0.5f;
                                }
                                catch (System.Exception e)
                                {
                                    Debug.LogWarning(e);
                                }
                            }
                        }
                    }
            }
            catch (WebException we)
            {
                Debug.LogWarning(we.StackTrace);
                Debug.LogWarning(we.Message);
                if (we.Status == WebExceptionStatus.Timeout && timedoutNum++ >= 5)
                {
                    hostTimedOut();
                    break;
                }
                // Possibly Host has quit game
                // Assume Host loses and client wins.
                //if (simulator!= null)
                //    simulator.commands.Add(new GameSetCmd(false));
            }
        }
        Debug.Log("Client thread ended");
    }