示例#1
0
        private void listenWatchConfirmation()
        {
            UdpClient client = null;

            try
            {
                client = new UdpClient(IN_PORT);
                client.Client.ReceiveTimeout = 1000;
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
                while (true)
                {
                    try
                    {
                        byte[] receivedBytes = client.Receive(ref endPoint);
                        parent.writeLog(LogLevel.Info, "Terima dari " + endPoint + ": " + Encoding.ASCII.GetString(receivedBytes));
                        JSONPacket inPacket = JSONPacket.createFromJSONBytes(receivedBytes);
                        if (inPacket.getParameter("type").Equals("pantau/confirm"))
                        {
                            if (inPacket.getParameter("status").Equals("ok") && inPacket.getParameter("gameid").Equals(controller.gameId))
                            {
                                String gameId = inPacket.getParameter("gameid");
                                int    ammo   = Int32.Parse(inPacket.getParameter("ammo"));
                                client.Close();
                                this.controller.startRegistration(gameId, ammo);
                            }
                            else
                            {
                                client.Close();
                                parent.showError("Pantau ditolak: " + inPacket.getParameter("status"));
                                parent.setWatchingEnabled(false);
                            }
                            return;
                        }
                        else
                        {
                            parent.writeLog(LogLevel.Warn, "Paket diabaikan karena belum memantau: " + inPacket);
                        }
                    }
                    catch (SocketException)
                    {
                        // void
                    }
                    catch (ThreadAbortException)
                    {
                        client.Close();
                        return;
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception e)
            {
                parent.writeLog(LogLevel.Error, "Error: " + e);
            }
        }
示例#2
0
        private void executePacketAndScheduleNext()
        {
            eventTimer.Enabled = false;
            bool updateUI = !(parent.skipRegistration && state == State.REGISTRATION);

            if (scheduledEvent != null)
            {
                if (updateUI)
                {
                    parent.updateReplayProgress(1e-3 * ((stopwatch.ElapsedMilliseconds + skippedMilliseconds) * parent.playSpeed));
                }
                if (scheduledEvent.packet.Equals(EventsRecorder.REGISTER))
                {
                    startRegistration(player.getProperty(EventsRecorder.PROP_GAMEID), Int32.Parse(player.getProperty(EventsRecorder.PROP_AMMO)));
                }
                else if (scheduledEvent.packet.StartsWith(EventsRecorder.START))
                {
                    string[] tokens = scheduledEvent.packet.Split('/');
                    for (int i = 0; i < tokens[1].Length; i++)
                    {
                        prajurits[i].group = "" + tokens[1][i];
                    }
                    startExercise();
                }
                else if (scheduledEvent.packet.Equals(EventsRecorder.STOP))
                {
                    stopExercise(true);
                }
                else
                {
                    parent.writeLog(LogLevel.Info, "Pura-pura terima dari " + scheduledEvent.sender + ": " + scheduledEvent.packet);
                    parent.pesertaDataGrid.Dispatcher.Invoke((Action)(() =>
                    {
                        this.handlePacket(scheduledEvent.sender, JSONPacket.createFromJSONBytes(Encoding.UTF8.GetBytes(scheduledEvent.packet)), updateUI);
                    }));
                }
            }
            Event nextEvent = player.getNextPlayEvent();

            if (nextEvent != null)
            {
                scheduledEvent = nextEvent;
                long currentTime = (long)((stopwatch.ElapsedMilliseconds + skippedMilliseconds) * parent.playSpeed);
                long interval    = (long)((nextEvent.timeOffset - currentTime) / parent.playSpeed);
                if (parent.skipRegistration && state == State.REGISTRATION)
                {
                    skippedMilliseconds += interval;
                    interval             = 0;
                }
                eventTimer.Interval = interval <= 0 ? 1 : interval;
                eventTimer.Enabled  = true;
            }
            else
            {
                stopPlayback();
            }
        }
示例#3
0
        public void watchExercise(String gameId)
        {
            JSONPacket packet = new JSONPacket("pantau/register");

            this.gameId = gameId;
            packet.setParameter("gameid", gameId);
            modifiedCommunication.broadcast(packet);
            modifiedCommunication.listenWatchConfirmationAsync(this);
            parent.setWatchingEnabled(true);
        }
示例#4
0
        private void sendEndGameSignals()
        {
            JSONPacket outPacket = new JSONPacket("endgame");

            foreach (Prajurit prajurit in prajurits)
            {
                communication.send(prajurit.ipAddress, outPacket);
                Thread.Sleep(100);
            }
        }
 public override void stopExercise(bool force)
 {
     base.stopExercise(force);
     foreach (IPAddress watcher in watchers)
     {
         JSONPacket packet = new JSONPacket("pantau/state");
         packet.setParameter("state", "STOP");
         parent.writeLog(LogLevel.Info, "Kirim ke pemantau " + watcher + " pesan " + packet);
         communication.send(watcher, packet, UDPCommunication.IN_PORT);
     }
 }
 public override void handlePacket(IPAddress address, JSONPacket inPacket, bool updateUI)
 {
     base.handlePacket(address, inPacket, updateUI);
     if (!inPacket.getParameter("type").StartsWith("pantau/"))
     {
         foreach (IPAddress watcher in watchers)
         {
             parent.writeLog(LogLevel.Info, "Kirim ke pemantau " + watcher + " pesan " + inPacket);
             communication.send(watcher, inPacket, UDPCommunication.IN_PORT);
         }
     }
 }
        public void send(IPAddress address, JSONPacket outPacket, int port)
        {
            UdpClient client     = new UdpClient(address + "", port);
            string    sendString = outPacket.ToString();

            Byte[] sendBytes = Encoding.UTF8.GetBytes(sendString);
            try
            {
                client.Send(sendBytes, sendBytes.Length);
                parent.writeLog(LogLevel.Info, "Kirim ke " + address + ":" + port + "/" + sendString);
            }
            catch (Exception e)
            {
                parent.writeLog(LogLevel.Error, "Error: " + e);
            }
        }
 public override void startExercise()
 {
     base.startExercise();
     foreach (IPAddress watcher in watchers)
     {
         JSONPacket packet     = new JSONPacket("pantau/state");
         string     teamGroups = "";
         for (int i = 0; i < prajurits.Count; i++)
         {
             teamGroups += prajurits[i].group;
         }
         packet.setParameter("state", "START/" + teamGroups);
         parent.writeLog(LogLevel.Info, "Kirim ke pemantau " + watcher + " pesan " + packet);
         communication.send(watcher, packet, UDPCommunication.IN_PORT);
     }
 }
示例#9
0
 public void broadcast(JSONPacket outPacket)
 {
     NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
     foreach (NetworkInterface Interface in Interfaces)
     {
         if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback)
         {
             continue;
         }
         if (Interface.OperationalStatus != OperationalStatus.Up)
         {
             continue;
         }
         Console.WriteLine(Interface.Description);
         UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
         HashSet <string> broadcastAddresses = new HashSet <string>();
         foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
         {
             byte[] ipAdressBytes = UnicatIPInfo.Address.GetAddressBytes();
             if (ipAdressBytes.Length > 4)
             {
                 continue;
             }
             byte[] subnetMaskBytes  = UnicatIPInfo.IPv4Mask.GetAddressBytes();
             byte[] broadcastAddress = new byte[ipAdressBytes.Length];
             for (int i = 0; i < broadcastAddress.Length; i++)
             {
                 broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); // OR ip address dengan subnet
             }
             String ipBroadcastStr = "";
             for (int i = 0; i < broadcastAddress.Length; i++) //for print only
             {
                 ipBroadcastStr += broadcastAddress[i] + ".";
             }
             broadcastAddresses.Add(ipBroadcastStr.Substring(0, ipBroadcastStr.Length - 1));
         }
         foreach (string addressStr in broadcastAddresses)
         {
             IPAddress ipBroadcast = IPAddress.Parse(addressStr);
             base.send(ipBroadcast, outPacket, UDPCommunication.IN_PORT);
             parent.writeLog(LogLevel.Info, "Broadcast ke " + ipBroadcast.ToString());
         }
     }
 }
示例#10
0
        // GET -> api/seticon | icon in params
        public static ResponseData SetIcon(Session session, Dictionary <string, string> kwargs)
        {
            string icon = kwargs["icon"];

            JSONFileService.Update(Guid.Parse(session.SessionData["UserID"]), icon);
            JSONPacket jp = new JSONPacket()
            {
                HasIcon = true, Redirect = "/welcome"
            };

            return(new ResponseData()
            {
                Data = Encoding.UTF8.GetBytes(jp.ToString()),
                Complete = true,
                ContentType = "text/json",
                Encoding = Encoding.UTF8,
                Status = ServerStatus.OK
            });
        }
        private void listen()
        {
            UdpClient client = null;

            try
            {
                client = new UdpClient(IN_PORT);
                client.Client.ReceiveTimeout = 1000;
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
                softAbort = false;
                while (!softAbort)
                {
                    try
                    {
                        byte[] receivedBytes = client.Receive(ref endPoint);
                        parent.writeLog(LogLevel.Info, "Terima dari " + endPoint + ": " + Encoding.ASCII.GetString(receivedBytes));
                        JSONPacket inPacket = JSONPacket.createFromJSONBytes(receivedBytes);
                        controller.handlePacket(endPoint.Address, inPacket, true);
                    }
                    catch (SocketException)
                    {
                        // void
                    }
                    catch (JsonReaderException jre)
                    {
                        parent.writeLog(LogLevel.Error, "Error: " + jre);
                    }
                }
                client.Close();
                parent.writeLog(LogLevel.Info, "Communcation soft-closed");
            }
            catch (ThreadAbortException)
            {
                client.Close();
                parent.writeLog(LogLevel.Info, "Communcation hard-closed");

                return;
            }
            catch (Exception e)
            {
                parent.writeLog(LogLevel.Error, "Error: " + e);
            }
        }
示例#12
0
        public override void send(IPAddress address, JSONPacket outPacket)
        {
            string sendString = outPacket.ToString();

            this.parent.writeLog(LogLevel.Info, "Pura-pura kirim ke " + address + ": " + sendString);
        }
示例#13
0
        // POST -> api/login | username and password in form data
        public static ResponseData LoginHandler(Session session, Dictionary <string, string> kwargs)
        {
            string username     = kwargs["username"];
            string password     = kwargs["password"];
            string submitButton = kwargs["operation"];
            string Status       = "";
            var    user         = JSONFileService.GetAll <User>().FirstOrDefault(user => user.Username == username);

            if (user != null)
            {
                if (submitButton == "register")
                {
                    Status = "Username already taken!";
                }
                else if (AesEncryptor.Compare(password, user))
                {
                    //successful login, redirect user to the app
                    session.Authorized = true;
                    session.SessionData.TryAdd("UserID", user.ID.ToString());
                    session.SessionData.TryAdd("Username", user.Username);
                    var dataPacket = new JSONPacket();
                    if (user.Icon != null)
                    {
                        dataPacket.Redirect = "/welcome";
                        dataPacket.HasIcon  = true;
                    }
                    else
                    {
                        dataPacket.HasIcon = false;
                    }
                    var ret = new ResponseData()
                    {
                        Data        = Encoding.UTF8.GetBytes(dataPacket.ToString()),
                        ContentType = "text/json",
                        Complete    = true,
                        Status      = ServerStatus.OK,
                        Encoding    = Encoding.UTF8
                    };
                    return(ret);
                }
                else
                {
                    Status = "Wrong password!";
                }
            }
            else
            {
                if (submitButton == "login")
                {
                    Status = "No such user exists!";
                }
                else
                {
                    if (ParseCredentials(username, password))
                    {
                        Status = "Registered new user!";
                        user   = new User
                        {
                            Username    = username,
                            Password    = password,
                            DateCreated = DateTime.UtcNow.ToString()
                        };
                        AesEncryptor.Encrypt(user);
                        JSONFileService.Add(user);
                    }
                    else
                    {
                        Status = "Username and password cannot be empty!";
                    }
                }
            }
            var dataWrapper = new JSONPacket()
            {
                Data = Status, Redirect = null, HasIcon = true
            };

            return(new ResponseData()
            {
                ContentType = "text/json",
                Encoding = Encoding.UTF8,
                Data = Encoding.UTF8.GetBytes(dataWrapper.ToString()),
                Status = ServerStatus.OK,
                Complete = true
            });
        }
示例#14
0
        public virtual void handlePacket(IPAddress address, JSONPacket inPacket, bool updateUI)
        {
            try
            {
                this.recorder.record(address, inPacket.ToString());
                String type = inPacket.getParameter("type");
                if (type.Equals("register"))
                {
                    if (inPacket.getParameter("gameid").Equals(gameId))
                    {
                        if (state == State.REGISTRATION)
                        {
                            int nomerUrut = Prajurit.findPrajuritIndexByNomerInduk(prajurits, inPacket.getParameter("nomerInduk"));
                            if (nomerUrut == -1)
                            {
                                // Register
                                nomerUrut = prajurits.Count + 1;
                                Prajurit newPrajurit = new Prajurit(nomerUrut, inPacket.getParameter("nomerInduk"), address, "A", null);
                                prajuritDatabase.retrieveNameFromDatabase(newPrajurit);
                                prajurits.Add(newPrajurit);
                                if (updateUI)
                                {
                                    parent.refreshTable();
                                }
                            }
                            else
                            {
                                nomerUrut = nomerUrut + 1;
                            }

                            // Confirm
                            JSONPacket outPacket = new JSONPacket("confirm");
                            outPacket.setParameter("androidId", "" + nomerUrut);
                            communication.send(address, outPacket);
                        }
                        else
                        {
                            parent.writeLog(LogLevel.Warn, "Registration from " + address + " is ignored as we are not in registration phase");
                        }
                    }
                    else
                    {
                        parent.writeLog(LogLevel.Warn, "Registration from " + address + " with game id " + inPacket.getParameter("gameid") + " is ignored");
                    }
                }
                else if (type.Equals("event/update"))
                {
                    if (inPacket.getParameter("gameid").Equals(gameId))
                    {
                        if (state != State.IDLE)
                        {
                            int      index    = Int32.Parse(inPacket.getParameter("androidId")) - 1;
                            Prajurit prajurit = prajurits[index];
                            prajurit.setLocation(inPacket.getParameter("location"));
                            prajurit.heading  = Double.Parse(inPacket.getParameter("heading"));
                            prajurit.accuracy = Int32.Parse(inPacket.getParameter("accuracy"));
                            string[] prajuritState = inPacket.getParameter("state").Split('/');
                            prajurit.state   = (prajuritState[0].Equals("alive") ? Prajurit.State.NORMAL : Prajurit.State.DEAD);
                            prajurit.posture = (prajuritState[1].Equals("stand") ? Prajurit.Posture.STAND : Prajurit.Posture.CRAWL);
                            if (inPacket.getParameter("action").Equals("hit"))
                            {
                                int idSenjata = Int32.Parse(inPacket.getParameter("idsenjata"));
                                int counter   = Int32.Parse(inPacket.getParameter("counter"));
                                if (state == State.REGISTRATION)
                                {
                                    // Registration phase, senjata assign to prajurit.
                                    Senjata newSenjata = new Senjata(idSenjata, prajurit, counter, this.initialAmmo);
                                    prajurit.senjata = newSenjata;
                                    senjatas.Add(newSenjata.idSenjata, newSenjata);
                                }
                                else if (state == State.EXERCISE)
                                {
                                    Senjata senjataPenembak = senjatas[idSenjata];
                                    senjataPenembak.currentCounter = counter;
                                    if (senjataPenembak.getRemainingAmmo() > 0)
                                    {
                                        prajurit.state = Prajurit.State.HIT;
                                        communication.send(prajurit.ipAddress, new JSONPacket("killed"));
                                    }
                                }
                                parent.refreshTable();
                            }
                            else if (inPacket.getParameter("action").Equals("shoot"))
                            {
                                prajurit.state = Prajurit.State.SHOOT;
                            }
                            if (updateUI)
                            {
                                parent.mapDrawer.updateMap(prajurit);
                                parent.refreshTable();
                            }
                        }
                        else
                        {
                            parent.writeLog(LogLevel.Warn, "Update event is ignored when state is idle.");
                        }
                    }
                    else
                    {
                        parent.writeLog(LogLevel.Warn, "Event update from " + address + " with game id " + inPacket.getParameter("gameid") + " is ignored");
                    }
                }
                else if (type.Equals("ping"))
                {
                    // Reply with pong, and let the rest of parameters be the same.
                    inPacket.setParameter("type", "pong");
                    communication.send(address, inPacket);
                }
                else if (type.Equals("pantau/register"))
                {
                    if (inPacket.getParameter("gameid").Equals(gameId))
                    {
                        JSONPacket outPacket = new JSONPacket("pantau/confirm");
                        if (state == State.REGISTRATION && prajurits.Count == 0)
                        {
                            watchers.Add(address);
                            outPacket.setParameter("status", "ok");
                            outPacket.setParameter("gameid", gameId);
                            outPacket.setParameter("ammo", "" + initialAmmo);
                        }
                        else
                        {
                            outPacket.setParameter("status", "Tidak bisa pantau karena sudah ada prajurit yang bergabung atau latihan sudah dimulai.");
                        }
                        communication.send(address, outPacket, UDPCommunication.IN_PORT);
                        parent.writeLog(LogLevel.Info, address + " joined as watcher");
                    }
                    else
                    {
                        parent.writeLog(LogLevel.Warn, "Watch request from " + address + " is ignored, as the game id " + inPacket.getParameter("gameid") + " mismatched");
                    }
                }
                else if (type.Equals("pantau/state"))
                {
                    if (inPacket.getParameter("state").StartsWith("START"))
                    {
                        string[] tokens = inPacket.getParameter("state").Split('/');
                        for (int i = 0; i < tokens[1].Length; i++)
                        {
                            prajurits[i].group = "" + tokens[1][i];
                        }
                        startExercise();
                    }
                    else if (inPacket.getParameter("state").Equals("STOP"))
                    {
                        stopExercise(false);
                    }
                    else
                    {
                        parent.writeLog(LogLevel.Error, "Unknown state set: " + inPacket.getParameter("state"));
                    }
                }
                else
                {
                    parent.writeLog(LogLevel.Error, "Unknown type: " + type);
                }
            }
            catch (Exception e)
            {
                parent.writeLog(LogLevel.Error, "Unhandled exception: " + e);
            }
        }
 public virtual void send(IPAddress address, JSONPacket outPacket)
 {
     send(address, outPacket, OUT_PORT);
 }