示例#1
0
        private void LocalState(string pid, string round_id)
        {
            try
            {
                IPCS          pcs    = pcsByPID[pid];
                List <String> result = pcs.LocalState(pid, round_id);

                if (result != null)
                {
                    string path = "..\\..\\LocalState-" + pid + '-' + round_id;
                    using (StreamWriter file = new StreamWriter(@path, false))
                    {
                        result.ForEach((line) =>
                        {
                            file.WriteLine(line);
                            //TODO Uncomment before submiting the project !
                            Console.WriteLine(line);
                        });
                    }
                }
            }
            catch (KeyNotFoundException e)
            {
                Console.WriteLine("Unknown PID: {0}", pid);
            }
        }
示例#2
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private void UnfreezeButton_Click(object sender, EventArgs e)
        {
            if (pcsListBox.SelectedItem == null ||
                serverList.SelectedItem == null)
            {
                return;
            }
            string server_id = (string)serverList.SelectedItem;
            string pcsUrl    = (string)pcsListBox.SelectedItem;
            IPCS   pcs       = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            try
            {
                ServerCommandAsync async    = new ServerCommandAsync(pcs.Unfreeze);
                IAsyncResult       asyncRes = async.BeginInvoke(server_id, null, null);
                asyncRes.AsyncWaitHandle.WaitOne();
                async.EndInvoke(asyncRes);
                outputBox.Text += "Successfully unfrozen " + server_id + "\r\n";
            }
            catch (SocketException)
            {
                MessageBox.Show("Could not locate selected PCS",
                                "Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#3
0
        private IPCS GetPCS(string URL)
        {
            string ip = Interfaces.URL.GetIP(URL);

            if (_PCSs.ContainsKey(ip))
            {
                return(_PCSs[ip]);
            }

            string PCS_URL = "tcp://" + ip + ":10000/PCS";

            IPCS pcs = (IPCS)Activator.GetObject(typeof(IPCS), PCS_URL);

            //weak check
            if (pcs == null)
            {
                Console.WriteLine("Failed to connect to PCS at " + PCS_URL);
                return(null);
            }

            Console.WriteLine("Connected to PCS at " + PCS_URL);

            _PCSs.Add(ip, pcs);

            return(pcs);
        }
示例#4
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private void CreateServerButton_Click(object sender, EventArgs e)
        {
            if (pcsListBox.SelectedItem == null)
            {
                return;
            }
            else if (serverID.Text.Length == 0 || serverURL.Text.Length == 0 ||
                     maxFaults.Text.Length == 0 || minDelays.Text.Length == 0 || maxDelays.Text.Length == 0)
            {
                return;
            }

            int faultsMax = 0, delaysMax = 0, delaysMin = 0;

            try
            {
                faultsMax = Int32.Parse(maxFaults.Text);
                delaysMax = Int32.Parse(maxDelays.Text);
                delaysMin = Int32.Parse(minDelays.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Max faults, max delays and min delays need to be numeric",
                                "Format Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (OverflowException)
            {
                MessageBox.Show("Max faults, max delays or min delays overflowed",
                                "Overflow Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string pcsUrl = (string)pcsListBox.SelectedItem;
            IPCS   pcs    = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            outputBox.Text         += "Creating server " + serverID.Text + "...\r\n";
            createServerBox.Enabled = false;
            try
            {
                CreateServerAsync async    = new CreateServerAsync(pcs.Server);
                IAsyncResult      asyncRes = async.BeginInvoke(serverID.Text, serverURL.Text,
                                                               faultsMax, delaysMin, delaysMax, null, null);
                asyncRes.AsyncWaitHandle.WaitOne();
                async.EndInvoke(asyncRes);
                servers.Add(serverID.Text, serverURL.Text);
                outputBox.Text += "Server " + serverID.Text + " successfully created\r\n";
            }
            catch (SocketException)
            {
                MessageBox.Show("Could not locate selected PCS",
                                "Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            serverID.Text           = "";
            serverURL.Text          = "";
            maxFaults.Text          = "";
            minDelays.Text          = "";
            maxDelays.Text          = "";
            createServerBox.Enabled = true;
        }
示例#5
0
 private void Freeze(string pid)
 {
     try
     {
         IPCS pcs = pcsByPID[pid];
         pcs.Freeze(pid);
     }
     catch (KeyNotFoundException e)
     {
         Console.WriteLine("Unknown PID: {0}", pid);
     }
 }
示例#6
0
        public static void cmdStartClient(string pid, string pcs_url, string client_url, int msec_per_round, int num_players, string path, int src)
        {
            pidToUrl.Add(pid, client_url);
            activeClient.Add(client_url);

            printPM("Starting Client", src);
            printPM("Checking for PCS", src);

            remote = checkPCS(pcs_url);
            //Console.WriteLine(pcs_url);

            remote.createReplica(pid, pcs_url, client_url, msec_per_round, num_players, 1, path);
        }
示例#7
0
 private void StartServer(string pid, string pcs_url, string server_url, string msec, string num_players)
 {
     try
     {
         IPCS pcs = getOrConnectToPCS(pcs_url);
         pcs.StartServer(pid, server_url, msec, num_players);
         knownServers.Add(server_url);
         pcsByPID[pid] = pcs;
     }
     catch (UriFormatException e)
     {
         Console.WriteLine("Invalid PCS_URL: {0}", e);
     }
 }
示例#8
0
        public static void cmdStartServer(string pid, string pcs_url, string server_url, int msec_per_round, int num_players, int src)
        {
            pidToUrl.Add(pid, server_url);
            activeServer.Add(server_url);

            printPM("Starting Server", src);
            printPM("Checking for PCS", src);

            remote = checkPCS(pcs_url);
            //Console.WriteLine(pcs_url);

            setServerPort(server_url);

            remote.createReplica(pid, pcs_url, server_url, msec_per_round, num_players, 0, "");
        }
示例#9
0
        static IPCS getIPCS()
        {
            IPCS ipcs = null;

            try
            {
                ipcs = (IPCS)Activator.GetObject(typeof(IPCS), ConnectionLibrary.buildPCSURL());
            }
            catch (Exception)
            {
                Console.WriteLine("Couldn't find IPS.");
            }

            return(ipcs);
        }
示例#10
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private IPCS GetPCSFromHostname(string url)
        {
            IPCS pcs = null;

            foreach (string pcs_url in pcsListBox.Items)
            {
                Uri pcsUri    = new Uri(pcs_url);
                Uri serverUri = new Uri(url);
                if (Uri.Compare(pcsUri, serverUri, UriComponents.Host, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    pcs = (IPCS)Activator.GetObject(typeof(IPCS), pcs_url);
                }
            }

            return(pcs);
        }
示例#11
0
 private IPCS getOrConnectToPCS(string pcs_url)
 {
     try
     {
         return(pcsByUrl[pcs_url]);
     }
     catch (KeyNotFoundException e)
     {
         new Uri(pcs_url);
         Console.WriteLine("Connecting to {0}", pcs_url);
         IPCS pcs = Activator.GetObject(typeof(PCSService), pcs_url) as IPCS;
         pcs.Print("Hello there :)");
         pcsByUrl.Add(pcs_url, pcs);
         return(pcs);
     }
 }
示例#12
0
 private static IPCS ConnectToPCS(RemotingAddress PCSRemotingAddress)
 {
     if (!PCSList.Exists(x => x.Item1 == PCSRemotingAddress))
     {
         IPCS pcs = (IPCS)Activator.GetObject(typeof(IPCS), PCSRemotingAddress.ToString());
         if (pcs == null)
         {
             throw new ApplicationException("Could not locate PCS: " + PCSRemotingAddress.ToString());
         }
         PCSList.Add(new Tuple <RemotingAddress, IPCS>(PCSRemotingAddress, pcs));
         return(pcs);
     }
     else
     {
         return(PCSList.Find(x => x.Item1 == PCSRemotingAddress).Item2);
     }
 }
示例#13
0
        public static void CreateServer(string serverID, RemotingAddress serverRA,
                                        uint maxFaults, uint minDelay, uint maxDelay)
        {
            if (serverList.Exists(x => x.Item1 == serverID))
            {
                throw new ApplicationException($"Server with ID '{serverID}' already exists.");
            }

            RemotingAddress pcsRA = new RemotingAddress(serverRA.address, PCSPort, PCSChannel);

            IPCS pcs = GetPCS(pcsRA);

            try
            {
                pcs.StartServer(serverID, serverRA, maxFaults, minDelay, maxDelay);
            }
            catch (System.Net.Sockets.SocketException)
            {
                MessageBox.Show($"Connection with PCS on remoting address '{pcsRA.ToString()}' was lost.\n" +
                                "If the PCS has been restarted you may try again.");
                Program.RemovePCSFromList(pcsRA);
                return;
            }

            IServerPM server = ConnectToServer(serverID, serverRA);

            //Replication
            //Inform new server of all existing servers
            server.SendExistingServersList(remoteServerList);
            //Inform all existing servers of new server
            foreach (Tuple <string, RemotingAddress, IServerPM> serv in serverList)
            {
                serv.Item3.BroadcastNewServer(new Tuple <string, RemotingAddress>(serverID, serverRA));
            }


            // Fill location list
            if (serverList.Count == 1)
            {
                mainForm.manageServersPage.FillLocationCb(server.GetLocationsPM());
            }

            mainForm.manageServersPage.AddServerToList(serverID);
        }
示例#14
0
        public static void CreateClient(string username, RemotingAddress clientRA,
                                        RemotingAddress serverRA, string scriptFile)
        {
            RemotingAddress pcsRA = new RemotingAddress(serverRA.address, PCSPort, PCSChannel);

            IPCS pcs = GetPCS(pcsRA);

            try
            {
                pcs.StartClient(username, clientRA, serverRA, scriptFile);
            }
            catch (System.Net.Sockets.SocketException)
            {
                MessageBox.Show($"Connection with PCS on remoting address '{pcsRA.ToString()}' was lost.\n" +
                                "If the PCS has been restarted you may try again.");
                Program.RemovePCSFromList(pcsRA);
                return;
            }
        }
示例#15
0
 private void StartClient(string pid, string pcs_url, string client_url, string msec, string num_players, string file_name)
 {
     try
     {
         IPCS pcs = getOrConnectToPCS(pcs_url);
         try
         {
             string server_url = knownServers[0];
             pcs.StartClient(pid, client_url, msec, num_players, file_name, server_url);
             pcsByPID[pid] = pcs;
         }
         catch (ArgumentOutOfRangeException e)
         {
             Console.WriteLine("No known servers. Please start a server first.");
         }
     }
     catch (UriFormatException e)
     {
         Console.WriteLine("Invalid PCS_URL: {0}", pcs_url);
     }
 }
示例#16
0
        static public IPCS checkPCS(string pcs_url)
        {
            if (pcsList.Any(item => item.Equals(pcs_url)))
            {
                return(pcs[pcs_url]);
            }
            else
            {
                if (pcsAlive == 1)
                {
                    pcsList.Remove(pcs_url);
                    pcs.Remove(pcs_url);
                    remote = RemotingServices.Connect(typeof(IPCS),
                                                      "tcp://localhost:11000/PCS") as IPCS;
                    try
                    {
                        remote.close();
                    }
                    catch { }

                    //System.Threading.Thread.Sleep(5000);
                    pcsAlive = 0;
                }
                ProcessStartInfo info = new ProcessStartInfo(PCS.exe_path(), pcs_url);
                info.CreateNoWindow = false;

                remote = RemotingServices.Connect(typeof(IPCS),
                                                  "tcp://localhost:11000/PCS") as IPCS;

                pcsList.Add(pcs_url);
                pcs.Add(pcs_url, remote);

                pcsAlive = 1;
                Process.Start(info);


                return(pcs[pcs_url]);
            }
        }
示例#17
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private void CreateClientButton_Click(object sender, EventArgs e)
        {
            if (pcsListBox.SelectedItem == null)
            {
                return;
            }
            else if (clientUsername.Text.Length == 0 || clientURL.Text.Length == 0 ||
                     clientServerURL.Text.Length == 0 || clientScript.Text.Length == 0)
            {
                return;
            }

            string pcsUrl = (string)pcsListBox.SelectedItem;
            IPCS   pcs    = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            outputBox.Text         += "Creating client " + clientUsername.Text + "...\r\n";
            createClientBox.Enabled = false;
            try
            {
                CreateClientAsync async    = new CreateClientAsync(pcs.Client);
                IAsyncResult      asyncRes = async.BeginInvoke(clientUsername.Text, clientURL.Text,
                                                               clientServerURL.Text, clientScript.Text, null, null);
                asyncRes.AsyncWaitHandle.WaitOne();
                async.EndInvoke(asyncRes);
                outputBox.Text += "Client " + clientUsername.Text + " successfully created\r\n";
                clients.Add(clientUsername.Text, clientURL.Text);
            }
            catch (SocketException)
            {
                MessageBox.Show("Could not locate selected PCS",
                                "Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            clientUsername.Text     = "";
            clientURL.Text          = "";
            clientServerURL.Text    = "";
            clientScript.Text       = "";
            createClientBox.Enabled = true;
        }
示例#18
0
        public void Server(string server_id, string URL, int min_delay, int max_delay)
        {
            string urlPcs = URL.Split(':')[0] + ":" + URL.Split(':')[1] + ":10000/pcs";

            if (processNames.ContainsKey(server_id))
            {
                Console.WriteLine("Server ID already exists");
                return;
            }
            IPCS pcs = null;

            pcs = (IPCS)Activator.GetObject(typeof(IPCS), urlPcs);
            string type = pcs.Server(URL, min_delay, max_delay);

            if (type == "SMR")
            {
                processNames.Add(server_id, new Process(URL, Process.Type.SERVER_SMR));
            }
            else if (type == "XL")
            {
                processNames.Add(server_id, new Process(URL, Process.Type.SERVER_XL));
            }
        }
示例#19
0
        public ServerInfo createServer(string server_id, string server_url, string max_faults,
                                       string min_delay, string max_delay)
        {
            //tcp://localhost:3000/server1 needs to be parsed
            //connect to correct pcs
            string[] urlParsed = server_url.Split(':');
            string   pcsUrl    = urlParsed[0] + ':' + urlParsed[1] + ':' + "10000/PCS";
            IPCS     pcs       = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            //create server
            ServerInfo serverInfo;

            try{
                serverInfo = pcs.createServer(server_id, server_url,
                                              max_faults, min_delay, max_delay);
            } catch (Exception ex) {
                //TODO catch PCS types of execeptions
                Log.Error(ex, "pcs connection failed");
                throw new PCSException("pcs connection failed", ex);
            }
            //save server
            serverList.Add(server_id, serverInfo);

            //send all available rooms
            IServerPuppeteer server = (IServerPuppeteer)Activator.GetObject(
                typeof(IServerPuppeteer),
                serverInfo.url_puppeteer);

            try{
                //Thread.Sleep(50); //TODO: make async
                server.populate(locationList, serverList);
            } catch (Exception ex) {
                Log.Error(ex, "connection to server failed");
            }

            return(serverInfo);
        }
示例#20
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private void ShowServers_Click(object sender, EventArgs e)
        {
            if (pcsListBox.SelectedItem == null)
            {
                return;
            }
            string pcsUrl = (string)pcsListBox.SelectedItem;
            IPCS   pcs    = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            outputBox.Text += "Getting servers from selected PCS...\r\n";
            try
            {
                GetServersAsync async    = new GetServersAsync(pcs.GetServers);
                IAsyncResult    asyncRes = async.BeginInvoke(null, null);
                asyncRes.AsyncWaitHandle.WaitOne();
                BindingList <string> serversDataSource = new BindingList <string>(async.EndInvoke(asyncRes));
                serverList.DataSource = serversDataSource;
            }
            catch (SocketException)
            {
                MessageBox.Show("Could not locate selected PCS",
                                "Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#21
0
        private IPCS GetPCS(string pcs_URL)
        {
            string ip = URL.GetIP(pcs_URL);

            if (_PCSs.ContainsKey(ip))
            {
                return(_PCSs[ip]);
            }

            IPCS pcs = (IPCS)Activator.GetObject(typeof(IPCS), pcs_URL);

            //weak check
            if (pcs == null)
            {
                Console.WriteLine("Failed to connect to PCS at " + pcs_URL);
                return(null);
            }

            Console.WriteLine("Connected to PCS at " + pcs_URL);

            _PCSs.Add(ip, pcs);

            return(pcs);
        }
示例#22
0
        public ClientInfo createClient(string username, string client_url, string server_url,
                                       string script_file)
        {
            //connect to correct pcs
            string[] urlParsed = server_url.Split(':');
            string   pcsUrl    = urlParsed[0] + ':' + urlParsed[1] + ':' + "10000/PCS";
            IPCS     pcs       = (IPCS)Activator.GetObject(typeof(IPCS), pcsUrl);

            //create client
            ClientInfo clientInfo;

            try{
                clientInfo = pcs.createClient(username, client_url, server_url,
                                              script_file);
            } catch (Exception ex) {
                //TODO catch PCS types of execeptions
                Log.Error(ex, "pcs connection failed");
                throw new PCSException("pcs connection failed", ex);
            }

            //save client
            clientList.Add(username, clientInfo);
            return(clientInfo);
        }
示例#23
0
        public void Client(string client_id, string URL, string script_file)
        {
            if (processNames.ContainsKey(client_id))
            {
                Console.WriteLine("Client ID already exists");
                return;
            }
            string urlPcs = URL.Split(':')[0] + ":" + URL.Split(':')[1] + ":10000/pcs";

            IPCS pcs = null;

            pcs = (IPCS)Activator.GetObject(typeof(IPCS), urlPcs);
            string type = pcs.Client(URL, script_file, XLFEcounter);

            if (type == "SMR")
            {
                processNames.Add(client_id, new Process(URL, Process.Type.CLIENT_SMR));
            }
            else if (type == "XL")
            {
                processNames.Add(client_id, new Process(URL, Process.Type.CLIENT_XL));
                XLFEcounter++;
            }
        }
示例#24
0
文件: Form1.cs 项目: jplmoreira/MSDAD
        private void RunScriptButton_Click(object sender, EventArgs e)
        {
            if (scriptBox.TextLength == 0)
            {
                return;
            }

            outputBox.Text += "Reading " + scriptBox.Text + "...\r\n";
            try
            {
                IPCS     pcs       = null;
                string[] fileLines = File.ReadAllLines(scriptBox.Text);
                foreach (string line in fileLines)
                {
                    string[] commandLine = line.Split(' ');
                    if (commandLine.Length <= 0)
                    {
                        continue;
                    }

                    outputBox.Text += "Running command " + commandLine[0] + "\r\n";
                    switch (commandLine[0])
                    {
                    case "PCS":
                        if (commandLine.Length == 2)
                        {
                            pcs = (IPCS)Activator.GetObject(typeof(IPCS), commandLine[1]);
                        }
                        else
                        {
                            outputBox.Text += "ERROR - PCS usage: PCS <pcs_url>\r\n";
                            return;
                        }
                        break;

                    case "Server":
                        if (commandLine.Length == 6)
                        {
                            // find the pcs with a matching hostname
                            pcs = GetPCSFromHostname(commandLine[2]);
                            try
                            {
                                pcs.Server(commandLine[1], commandLine[2], Int32.Parse(commandLine[3]),
                                           Int32.Parse(commandLine[4]), Int32.Parse(commandLine[5]));
                                servers.Add(commandLine[1], commandLine[2]);
                            }
                            catch (Exception)
                            {
                                outputBox.Text += "ERROR - must be connected to PCS\r\n";
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - Server usage: Server <server_id> <URL> <max_faults> <min_delay> <max_delay>\r\n";
                            return;
                        }
                        break;

                    case "Client":
                        if (commandLine.Length == 5)
                        {
                            // find the pcs with a matching hostname
                            pcs = GetPCSFromHostname(commandLine[2]);
                            try
                            {
                                pcs.Client(commandLine[1], commandLine[2], commandLine[3], commandLine[4]);
                                clients.Add(commandLine[1], commandLine[2]);
                            }
                            catch (Exception)
                            {
                                outputBox.Text += "ERROR - must be connected to PCS\r\n";
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - Client usage: Client <username> <client_URL> <server_URL> <script_file>\r\n";
                            return;
                        }
                        break;

                    case "AddRoom":
                        if (commandLine.Length == 4)
                        {
                            foreach (var server in servers)
                            {
                                // server.Key -> id
                                // server.Value -> url

                                IServer serverObj = (IServer)Activator.GetObject(typeof(IServer), server.Value);

                                try
                                {
                                    AddRoomAsync async    = new AddRoomAsync(serverObj.AddRoom);
                                    IAsyncResult asyncRes = async.BeginInvoke(commandLine[1], Int32.Parse(commandLine[2]), commandLine[3], null, null);
                                    asyncRes.AsyncWaitHandle.WaitOne();
                                    async.EndInvoke(asyncRes);
                                    outputBox.Text += $"Added room <{roomLocation.Text},{roomName.Text}> to server <{server.Key},{server.Value}> \r\n";
                                }
                                catch (SocketException)
                                {
                                    outputBox.Text += $"[Socket Exception] Could not locate <{ server.Key},{ server.Value}> \r\n";
                                }
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - AddRoom usage: AddRoom <location> <capacity> <room_name>\r\n";
                            return;
                        }
                        break;

                    case "Status":
                        int i = 0;
                        EventWaitHandle[] handles = new EventWaitHandle[servers.Count + clients.Count];
                        foreach (string server_url in servers.Values)
                        {
                            Thread task = new Thread(() =>
                            {
                                ((IServer)Activator.GetObject(typeof(IServer), server_url)).Status();
                                handles[i++].Set();
                            });
                        }

                        foreach (string client_url in clients.Values)
                        {
                            Thread task = new Thread(() =>
                            {
                                ((IServer)Activator.GetObject(typeof(IServer), client_url)).Status();
                                handles[i++].Set();
                            });
                        }

                        //WaitHandle.WaitAll(handles);
                        break;

                    case "Crash":
                        if (commandLine.Length == 2)
                        {
                            if (servers.TryGetValue(commandLine[1], out string server_url))
                            {
                                try
                                {
                                    ((IServer)Activator.GetObject(typeof(IServer), server_url)).Crash();
                                }
                                catch (SocketException)
                                {
                                    outputBox.Text += $"[Socket Exception] Could not locate <{commandLine[1]},{server_url}>\r\n";
                                }
                            }
                            else
                            {
                                outputBox.Text += "ERROR - server does not exist\r\n";
                                return;
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - Crash usage: Crash <server_id>\r\n";
                            return;
                        }
                        break;

                    case "Freeze":
                        if (commandLine.Length == 2)
                        {
                            if (servers.TryGetValue(commandLine[1], out string server_url))
                            {
                                try
                                {
                                    ((IServer)Activator.GetObject(typeof(IServer), server_url)).Freeze();
                                }
                                catch (SocketException)
                                {
                                    outputBox.Text += $"[Socket Exception] Could not locate <{commandLine[1]},{server_url}>\r\n";
                                }
                            }
                            else
                            {
                                outputBox.Text += "ERROR - server does not exist\r\n";
                                return;
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - Freeze usage: Freeze <server_id>\r\n";
                            return;
                        }
                        break;

                    case "Unfreeze":
                        if (commandLine.Length == 2)
                        {
                            if (servers.TryGetValue(commandLine[1], out string server_url))
                            {
                                try
                                {
                                    ((IServer)Activator.GetObject(typeof(IServer), server_url)).Unfreeze();
                                }
                                catch (SocketException)
                                {
                                    outputBox.Text += $"[Socket Exception] Could not locate <{commandLine[1]},{server_url}>\r\n";
                                }
                            }
                            else
                            {
                                outputBox.Text += "ERROR - server does not exist\r\n";
                                return;
                            }
                        }
                        else
                        {
                            outputBox.Text +=
                                "ERROR - Unfreeze usage: Unfreeze <server_id>\r\n";
                            return;
                        }
                        break;

                    case "Wait":
                        if (commandLine.Length == 2)
                        {
                            Thread.Sleep(Int32.Parse(commandLine[1]));
                        }
                        else
                        {
                            outputBox.Text += "ERROR - Wait usage: Wait <ms>\r\n";
                            return;
                        }
                        break;

                    default:
                        outputBox.Text += "Command not recognized\r\n";
                        break;
                    }
                }
            }
            catch (IOException)
            {
                outputBox.Text += "ERROR - Could not read file " + scriptBox.Text + "\r\n";
            }
            catch (FormatException formatException)
            {
                outputBox.Text += $"ERROR - Could not parse value: ${formatException}\r\n";
            }
            catch (SocketException)
            {
                outputBox.Text += "ERROR - Could not connecto to PCS\r\n";
            }
        }
示例#25
0
        static void Main(string[] args)
        {
            Dictionary <string, string> pid_Client = new Dictionary <string, string>();                                //PID,PCS_URL
            Dictionary <string, string> pid_Server = new Dictionary <string, string>();                                //PID,PCS_URL
            Dictionary <string, Tuple <bool, string> > url_Client  = new Dictionary <string, Tuple <bool, string> >(); //PID,CLIENT_URL
            Dictionary <string, Tuple <bool, string> > url_Servers = new Dictionary <string, Tuple <bool, string> >(); //PID,SERVER_URL


            TcpChannel channel = new TcpChannel();

            ChannelServices.RegisterChannel(channel, false);

            void process(string[] input)
            {
                IPCS pcs = null;

                switch (input[0])
                {
                case "StartClient":
                    if (url_Servers.Count == 0)
                    {
                        Console.WriteLine("Need to start one server first!");
                        break;
                    }
                    //StartClient PID PCS_URL CLIENT_URL MSEC_PER_ROUND NUM_PLAYERS [filename]
                    if (input.Count() > 7)
                    {
                        Console.WriteLine("Invalid number of arguments to start server, expected 5/6 delimited by a space");
                        break;
                    }
                    if (!pid_Client.ContainsKey(input[1]))
                    {
                        try
                        {
                            pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]);
                        }
                        catch (RemotingException)
                        {
                            Console.WriteLine("Problems getting Object IPCS interface from: " + input[2]);
                            break;
                        }
                        catch (ArgumentNullException)
                        {
                            Console.WriteLine("Url: " + input[2] + "or type is null.");
                            break;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Problems trying to get PCS, exception: ");
                            Console.WriteLine(e.ToString());
                            break;
                        }

                        string urlToSend = "";
                        foreach (Tuple <bool, string> url in url_Servers.Values)
                        {
                            if (!url.Item2.Equals(input[2]))
                            {
                                urlToSend += url.Item2 + ";";
                            }
                        }
                        if (!url_Client.ContainsKey(input[1]))
                        {
                            if (input.Count() == 6)
                            {
                                if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, "noFile"))
                                {
                                    pid_Client.Add(input[1], input[2]);
                                    url_Client.Add(input[1], new Tuple <bool, string>(true, input[3]));
                                    Console.WriteLine("Client with PID: " + input[1] + " started.");
                                }
                            }
                            if (input.Count() == 7)
                            {
                                if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, input[6]))
                                {
                                    pid_Client.Add(input[1], input[2]);
                                    url_Client.Add(input[1], new Tuple <bool, string>(true, input[3]));
                                    Console.WriteLine("Client with PID: " + input[1] + " started.");
                                }
                            }
                        }
                        if (url_Client.ContainsKey(input[1]) && !url_Client[input[1]].Item1)
                        {
                            if (input.Count() == 6)
                            {
                                if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, "noFile"))
                                {
                                    pid_Client.Add(input[1], input[2]);
                                    url_Client[input[1]] = new Tuple <bool, string>(true, input[3]);
                                    Console.WriteLine("Client with PID: " + input[1] + " started.");
                                }
                            }
                            if (input.Count() == 7)
                            {
                                if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, input[6]))
                                {
                                    pid_Client.Add(input[1], input[2]);
                                    url_Client[input[1]] = new Tuple <bool, string>(true, input[3]);
                                    Console.WriteLine("Client with PID: " + input[1] + " started.");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("PID already exists!");
                    }
                    break;

                case "StartServer":
                    //StartServer PID PCS_URL SERVER_URL MSEC_PER_ROUND NUM_PLAYERS
                    if (input.Count() > 6)
                    {
                        Console.WriteLine("Invalid number of arguments to start server, expected 5 delimited by a space");
                        break;
                    }
                    if (!pid_Server.ContainsKey(input[1]))
                    {
                        if (url_Servers.Count == 0)
                        {
                            try
                            {
                                pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]);
                            }
                            catch (RemotingException)
                            {
                                Console.WriteLine("Problems getting Object IPCS interface from: " + input[2]);
                                break;
                            }
                            catch (ArgumentNullException)
                            {
                                Console.WriteLine("Url: " + input[2] + "or type is null.");
                                break;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Problems trying to get PCS, exception: ");
                                Console.WriteLine(e.ToString());
                                break;
                            }
                            if (!url_Servers.ContainsKey(input[1]))
                            {
                                if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), ""))
                                {
                                    pid_Server.Add(input[1], input[2]);
                                    url_Servers.Add(input[1], new Tuple <bool, string>(true, input[3]));
                                    Console.WriteLine("Server with PID: " + input[1] + " started.");
                                }
                            }
                            if (url_Servers.ContainsKey(input[1]) && !url_Servers[input[1]].Item1)
                            {
                                if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), ""))
                                {
                                    pid_Server.Add(input[1], input[2]);
                                    url_Servers[input[1]] = new Tuple <bool, string>(true, input[3]);
                                    Console.WriteLine("Server with PID: " + input[1] + " started.");
                                }
                            }
                        }
                        else
                        {
                            pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]);
                            string urlToSend = "";
                            foreach (Tuple <bool, string> url in url_Servers.Values)
                            {
                                if (!url.Item2.Equals(input[2]))
                                {
                                    urlToSend += url.Item2 + ";";
                                }
                            }
                            if (!url_Servers.ContainsKey(input[1]))
                            {
                                if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend))
                                {
                                    pid_Server.Add(input[1], input[2]);
                                    url_Servers.Add(input[1], new Tuple <bool, string>(true, input[3]));
                                    Console.WriteLine("Server with PID: " + input[1] + " started.");
                                }
                            }
                            if (url_Servers.ContainsKey(input[1]) && !url_Servers[input[1]].Item1)
                            {
                                if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend))
                                {
                                    pid_Server.Add(input[1], input[2]);
                                    url_Servers[input[1]] = new Tuple <bool, string>(true, input[3]);
                                    Console.WriteLine("Server with PID: " + input[1] + " started.");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("PID already exists!");
                    }
                    break;

                case "GlobalStatus":
                    Parallel.ForEach(url_Servers, (s) =>
                    {
                        try
                        {
                            GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                                typeof(GameApi.IServerApi), s.Value.Item2);
                            Console.WriteLine(server.globalStatus());
                        }
                        catch
                        {
                            Console.WriteLine("Not Connected to Server: " + s.Key);
                        }
                        Console.WriteLine();
                    });
                    Console.WriteLine("CLIENTS");
                    Console.WriteLine();

                    Parallel.ForEach(url_Client, (c) =>
                    {
                        try
                        {
                            GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                                typeof(GameApi.IClientApi), c.Value.Item2);
                            Console.WriteLine(client.globalStatus());
                        }

                        catch
                        {
                            Console.WriteLine("Client with PID: " + c.Key + " crashed");
                        }
                        Console.WriteLine();
                    });
                    break;

                case "Crash":
                    if (pid_Server.ContainsKey(input[1]))
                    {
                        try
                        {
                            GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                                typeof(GameApi.IServerApi), url_Servers[input[1]].Item2);
                            if (server.crash())
                            {
                                Console.WriteLine("Problems trying to crash: " + input[1]);
                            }
                        }
                        catch
                        {
                            pid_Server.Remove(input[1]);
                            url_Servers[input[1]] = new Tuple <bool, string>(false, "");
                            Console.WriteLine("Server with PID: " + input[1] + " crashed");
                        }
                    }
                    else if (pid_Client.ContainsKey(input[1]))
                    {
                        try
                        {
                            GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                                typeof(GameApi.IClientApi), url_Client[input[1]].Item2);
                            if (client.crash())
                            {
                                Console.WriteLine("Problems trying to crash: " + input[1]);
                            }
                        }

                        catch
                        {
                            pid_Client.Remove(input[1]);
                            url_Client[input[1]] = new Tuple <bool, string>(false, "");
                            Console.WriteLine("Client with PID: " + input[1] + " crashed");
                        }
                    }
                    else
                    {
                        Console.WriteLine("PID do not exists!");
                    }
                    break;

                case "Freeze":
                    if (pid_Server.ContainsKey(input[1]))
                    {
                        GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                            typeof(GameApi.IServerApi), url_Servers[input[1]].Item2);
                        server.freeze(true);
                    }
                    else if (pid_Client.ContainsKey(input[1]))
                    {
                        GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                            typeof(GameApi.IClientApi), url_Client[input[1]].Item2);
                        client.freeze(true);
                    }
                    else
                    {
                        Console.WriteLine("PID do not exists!");
                    }
                    break;

                case "Unfreeze":
                    if (pid_Server.ContainsKey(input[1]))
                    {
                        GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                            typeof(GameApi.IServerApi), url_Servers[input[1]].Item2);
                        server.freeze(false);
                    }
                    else if (pid_Client.ContainsKey(input[1]))
                    {
                        GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                            typeof(GameApi.IClientApi), url_Client[input[1]].Item2);
                        client.freeze(false);
                    }
                    else
                    {
                        Console.WriteLine("PID do not exists!");
                    }
                    break;

                case "InjectDelay":
                    if (pid_Server.ContainsKey(input[1]))
                    {
                        GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                            typeof(GameApi.IServerApi), url_Servers[input[1]].Item2);
                        if (server.InjectDelay(input[1], input[2]))
                        {
                            Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + " added");
                        }
                        else
                        {
                            Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + "wasn't possible");
                        }
                    }
                    else if (pid_Client.ContainsKey(input[1]))
                    {
                        GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                            typeof(GameApi.IClientApi), url_Client[input[1]].Item2);
                        if (client.InjectDelay(pid_Server.Keys.First(), input[2]))
                        {
                            Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + " added");
                        }
                        else
                        {
                            Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + "wasn't possible");
                        }
                    }
                    break;

                case "LocalState":
                    String state = "";
                    if (input.Count() > 3)
                    {
                        Console.WriteLine("Invalid number of arguments to LocalState, expected 2 delimited by a space");
                        break;
                    }
                    if (pid_Server.ContainsKey(input[1]))
                    {
                        GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject(
                            typeof(GameApi.IServerApi), url_Servers[input[1]].Item2);
                        state = server.LocalState(Int32.Parse(input[2]));
                    }
                    else if (pid_Client.ContainsKey(input[1]))
                    {
                        GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject(
                            typeof(GameApi.IClientApi), url_Client[input[1]].Item2);
                        state = client.LocalState(Int32.Parse(input[2]));
                    }
                    if (!state.Equals(""))
                    {
                        Console.Write(state);
                        System.IO.File.WriteAllText(Environment.CurrentDirectory + @"\..\..\LocalState-" + input[1] + "-" + input[2] + ".txt", state);
                    }
                    else
                    {
                        Console.WriteLine("Local state for that PID does not exist");
                    }
                    break;

                case "Wait":
                    System.Threading.Thread.Sleep(Int32.Parse(input[1]));
                    break;

                default:
                    Console.WriteLine("Command not allowed");
                    break;
                }
            }

            for (;;)
            {
                Console.Write("-> ");
                String   command = Console.ReadLine();
                String[] words   = command.Split(delimiterChars);

                if (words[0].Equals("ReadFromScript"))
                {
                    Thread t1 = new Thread(() => {
                        String[] commands = System.IO.File.ReadAllLines(words[1]);
                        foreach (string s in commands)
                        {
                            process(s.Split(delimiterChars));
                        }
                    });
                    t1.Start();
                }
                else
                {
                    process(words);
                }
            }
        }