我聽的TCP端口,當我收到源IP第一,然後創建特殊類的新實例在第二包這個新的源IP插座及獲得衆多類具有相同的名稱
從源IP我並不需要創建類的新實例
我的問題是我怎麼能這樣第二個數據包傳遞給第i類的特別是源IP創建雖然我創造了許多類不同來源的ip
如果這是一個錯誤的方法,那麼最好的方法是什麼?
在此先感謝
我聽的TCP端口,當我收到源IP第一,然後創建特殊類的新實例在第二包這個新的源IP插座及獲得衆多類具有相同的名稱
從源IP我並不需要創建類的新實例
我的問題是我怎麼能這樣第二個數據包傳遞給第i類的特別是源IP創建雖然我創造了許多類不同來源的ip
如果這是一個錯誤的方法,那麼最好的方法是什麼?
在此先感謝
因此,你已經聽到了一個插座上的東西。當數據進入時,檢查源IP。如果它是一個新的IP,你實例化一個對象來處理它。展望未來,您希望來自該源IP的所有後續數據包轉到已經實例化的類,對嗎?
只給你的加工類別一個屬性,如SourceIp
。在最初接收數據包的類中創建所有實例化類的數組/列表。當數據包進入時,循環訪問數組並查看是否已有實例化對象。
UPDATE
我會在@擴大Justin的代碼一點點,但我認爲,一個Dictionary
可能是最好的類型。比方說,你有這個類處理包:
class Processor
{
public void ProcessPacket(Byte[] data)
{
//Your processing code here
}
}
首先,您需要到C 在代碼中接收數據我假設你有兩個數據本身以及源IP 。當接收數據時,你在字典中查找IP,並創建一個新的處理器或重新使用現有的一個:
//Holds our processor classes, each identified by IP
private Dictionary<IPAddress, Processor> Processors = new Dictionary<IPAddress,Processor>();
private void dataReceived(Byte[] data, IPAddress ip)
{
//If we don't already have the IP Address in our dictionary
if(!Processors.ContainsKey(ip)){
//Create a new processor object and add it to the dictionary
Processors.Add(ip, new Processor());
}
//At this point we've either just added a processor for this IP
//or there was one already in the dictionary so grab it based
//on the IP
Processor p = Processors[ip];
//Tell it to process our data
p.ProcessPacket(data);
}
嘗試使用Dictionary
存儲IP的地址映射爲處理對象。以下代碼中的類Session
對應於您的特殊處理類。其他類和屬性可能需要更改 - 如果需要更多細節,請提供一些代碼。
private Dictionary<IPAddress,Session> activeSessions = new Dictionary<IPAddress,Session>();
private void packetReceived(Packet pkt)
{
Session curSession;
if (!activeSessions.TryGetValue(pkt.SourceIP, out curSession))
{
curSession = new Session();
activeSessions.Add(pkt.SourceIP, curSession);
}
curSession.ProcessPacket(pkt);
}
你的問題沒有意義。 – SLaks 2011-01-13 18:44:08
的for(int i = 0; I <15;我++) \t \t \t { \t \t \t的Class1 X =新的Class1() \t \t \t}如何將一個值傳遞給第三實例(例如) – bebo 2011-01-13 18:53:58
我編輯我的問題,請再讀一遍 – bebo 2011-01-13 19:27:34