⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 Agent技术在智能交通中的应用
💻 CS
字号:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;

using MobileAgents;

namespace AgentClient
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			#region First Agent Sample...
            AgentProxy proxy = Agent.CreateAgent(typeof(MyFirstAgent));
            proxy.Move("tcp://localhost:10000/MyAgentSample");
			#endregion

			#region Traveling Agent Sample...
			//AgentProxy proxy = Agent.CreateAgent(typeof(MyTravelingAgent));
			//proxy.InvokeMethod("AddDestination", "tcp://localhost:10000/MyAgentSample");
			//proxy.InvokeMethod("AddDestination", "tcp://localhost:10002/MyAgentSample");
			//proxy.Move("tcp://localhost:10001/MyAgentSample");
			#endregion

			#region Master\Slave Task Agent Sample...
			//AgentProxy proxy = Agent.CreateAgent(typeof(MyMasterTaskAgent));
			//proxy.InvokeMethod("AddHost", "tcp://localhost:10000/MyAgentSample");
			//proxy.InvokeMethod("AddHost", "tcp://localhost:10001/MyAgentSample");
			//proxy.InvokeMethod("AddHost", "tcp://localhost:10002/MyAgentSample");
			//proxy.Move("tcp://localhost:10002/MyAgentSample");
			#endregion

			#region Buyer\Seller Interactive Agent Sample...
            //MySellingAgent seller1, seller2, seller3;
            //seller1 = new MySellingAgent
            //    (
            //    1,
            //    new MySellingAgent.ItemForSale[]
            //        {
            //            new MySellingAgent.ItemForSale("Mariners Tickets", 25),
            //            new MySellingAgent.ItemForSale("Sonics Tickets", 15)
            //        }
            //    );
            //seller1.Move("tcp://localhost:10000/MyAgentSample");

            //seller2 = new MySellingAgent
            //    (
            //    2,
            //    new MySellingAgent.ItemForSale[]
            //        {
            //            new MySellingAgent.ItemForSale("Mariners Tickets", 50),
            //            new MySellingAgent.ItemForSale("Sonics Tickets", 75)
            //        }
            //    );
            //seller2.Move("tcp://localhost:10001/MyAgentSample");

            //seller3 = new MySellingAgent
            //    (
            //    3,
            //    new MySellingAgent.ItemForSale[]
            //        {
            //            new MySellingAgent.ItemForSale("Mariners Tickets", 5),
            //            new MySellingAgent.ItemForSale("Sonics Tickets", 150)
            //        }
            //    );
            //seller3.Move("tcp://localhost:10002/MyAgentSample");


            //MyBuyingAgent buyer = new MyBuyingAgent
            //    (
            //    "Mariners Tickets",
            //    49,
            //    new string[]
            //        {
            //            "tcp://localhost:10002/MyAgentSample", 
            //            "tcp://localhost:10001/MyAgentSample", 
            //            "tcp://localhost:10000/MyAgentSample"
            //        }
            //    );
            //buyer.GoToMarketplace("tcp://localhost:10000/MyAgentSample");
			#endregion
		}
	}

	#region Agent Implementations...
	[Serializable()]
	class MyFirstAgent : MobileAgents.Agent
	{
		string _startingProcess = string.Empty;
		public MyFirstAgent()
		{
			_startingProcess = Process.GetCurrentProcess().ProcessName;
		}

		protected override void Run()
		{
			Console.WriteLine("I started in '{0}' but now am in '{1}'!", _startingProcess, Process.GetCurrentProcess().ProcessName);
		}
	}
	[Serializable()]
	class MyTravelingAgent : MobileAgents.Agent
	{
		Queue<string> _destinations = new Queue<string>();

		public void AddDestination(string url) {_destinations.Enqueue(url);}

		protected override void Run()
		{
			Console.WriteLine("I'm here now: {0}", DateTime.Now);

			//Simulate work... just for the effect of it.
			System.Threading.Thread.Sleep(5000);

			if (_destinations.Count > 0)
			{
				string nextDestination = _destinations.Dequeue();
				this.Move(nextDestination);
			}
		}
	}
	[Serializable()]
	class MyMasterTaskAgent : MobileAgents.Agent
	{
		List<string> _hostsToCheck = new List<string>();

		public void AddHost(string url){_hostsToCheck.Add(url);}

		protected override void Run()
		{
			foreach(string hostUrl in _hostsToCheck)
			{
				AgentProxy proxy = Agent.CreateAgent(typeof(MySlaveTaskAgent));
				proxy.Move(hostUrl);
			}
		}
	}
	[Serializable()]
	class MySlaveTaskAgent : MobileAgents.Agent
	{
		protected override void Run()
		{
			string[] drives = Directory.GetLogicalDrives();
			foreach(string drive in drives)
			{
				Console.WriteLine("Found drive: '{0}'", drive);
			}
		}
	}
	[Serializable()]
	class MySellingAgent : MobileAgents.Agent
	{
		#region Static Members...
		private static Dictionary<int, MySellingAgent> _sellers;
		static MySellingAgent() 
		{
			_sellers = new Dictionary<int, MySellingAgent>();
		}
		public static MySellingAgent[] GetSellersOnHost()
		{
			ArrayList sellers = new ArrayList(_sellers.Values);
			return (MySellingAgent[])sellers.ToArray(typeof(MySellingAgent));
		}
		public static MySellingAgent GetSellerById(int id)
		{
			if (_sellers.ContainsKey(id))
				return _sellers[id];
			else
				return null;
		}
		#endregion

		#region Instance Variables...
		private Dictionary<string, ItemForSale> _itemsForSell = new Dictionary<string, ItemForSale>();
		private int _id = 0;
		#endregion

		#region Instance Methods...
		public MySellingAgent(int id, ItemForSale[] itemsToSell)
		{
			this._id = id;

			foreach(ItemForSale item in itemsToSell) 
				_itemsForSell[item.ItemName] = item;
		}

		protected override void Run()
		{
			//Let's set up shop!
			_sellers.Add(this.Id, this);
			Console.WriteLine("Seller {0} has set up shop!", this.Id);

			//Optionally, do work to keep this thread alive.
			//I.e. monitor an external web site to get real-time
			//prices for items or tear down shop at closing time.
		}
		public bool IsItemForSale(string itemName)
		{
			return this._itemsForSell.ContainsKey(itemName);
		}
		public int GetItemPrice(string itemName)
		{
			int price = 0;

			if (this.IsItemForSale(itemName))
			{
				ItemForSale item = (ItemForSale)this._itemsForSell[itemName];
				price = item.ItemPrice;
			}

			return price;
		}
		public void BuyItem(string itemName)
		{
			//A real system would implement this by
			//decrementing inventory, charging an account, etc.
			if (this.IsItemForSale(itemName))
			{
				ItemForSale item = this._itemsForSell[itemName];
				Console.WriteLine("Customer bought '{0}' for ${1}", item.ItemName, item.ItemPrice);
			}
		}

		#endregion

		public int Id
		{
			get{return this._id;}
		}


		[Serializable()]
		public class ItemForSale
		{
			public ItemForSale(string name, int price)
			{
				this.ItemName = name;
				this.ItemPrice = price;
			}

			public string ItemName = string.Empty;
			public int ItemPrice = 0;
		}
	}
	[Serializable()]
	class MyBuyingAgent : MobileAgents.Agent
	{
		Queue<string> _sitesToVisit = new Queue<string>();

		string _itemToBuy = string.Empty;
		int _maxPriceForItem = 0;

		string _currentHost = string.Empty;

		string _winnerHost = string.Empty;
		int _winnerId = -1;
		int _winnerPrice = int.MaxValue;		


		public MyBuyingAgent(string itemToBuy, int maximumPriceForItem, string[] urlsToVisit)
		{
			this._itemToBuy = itemToBuy;
			this._maxPriceForItem = maximumPriceForItem;
			
			foreach(string url in urlsToVisit)
				_sitesToVisit.Enqueue(url);
		}

		protected override void Run()
		{
			Console.WriteLine("Buying agent is here.");

			//Sleep to help us visually see what is happening!
			System.Threading.Thread.Sleep(2000);	

			if (this._currentHost == this._winnerHost)
			{
				BuyFromWinner();
			}
			else
			{
				FindItem();
				if (_sitesToVisit.Count == 0)
					this.GoToMarketplace(this._winnerHost);
				else
				{
					string nextHost = this._sitesToVisit.Dequeue();
					this.GoToMarketplace(nextHost);
				}
			}
		}

		private void BuyFromWinner()
		{
			MySellingAgent seller = MySellingAgent.GetSellerById(this._winnerId);
			if (seller == null)
			{
				//Maybe the seller closed shop before we returned.
			}
			else
			{
				seller.BuyItem(this._itemToBuy);
				Console.WriteLine("We bought '{0}' from seller {1} at {2} for ${3}!", this._itemToBuy, this._winnerId, this._winnerHost, this._winnerPrice);
			}
		}
		private void FindItem()
		{
			MySellingAgent[] sellers = MySellingAgent.GetSellersOnHost();	
			
			foreach(MySellingAgent seller in sellers)
			{
				if (seller.IsItemForSale(this._itemToBuy))
				{
					int sellersPrice = seller.GetItemPrice(this._itemToBuy);
					if (sellersPrice <= this._maxPriceForItem)
					{
						if ((_winnerId == -1) || (sellersPrice < _winnerPrice))
						{
							this._winnerHost = this._currentHost;
							this._winnerId = seller.Id;
							this._winnerPrice = sellersPrice;
						}
					}
				}
			}
		}
		public void GoToMarketplace(string hostUrl)
		{
			this._currentHost = hostUrl;
			this.Move(this._currentHost);
		}
	}
	#endregion
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -