我听的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