网络流程

Vau*_*lts 1 c# networking xna lidgren

我正在用C#设计一款游戏,我相信你会得到很多 - 但我的问题有点不同,因为我想根据我的理解设计一些观察者模式的东西 - 我找不到太多的信息.

我的所有数据包都实现了一个名为IPacket的基本接口......我希望在收到某种类型的数据包时触发事件.没有使用大型开关.

我也许希望有类似的东西:

networkEvents.PacketRecieved + = [...]

任何人都可以指出我这样做的方向吗?

Hen*_*use 5

这样的事情怎么样:

public interface IPacket
{

}

public class FooPacket: IPacket {}

public class PacketService
{
    private static readonly ConcurrentDictionary<Type, Action<IPacket>> _Handlers = new ConcurrentDictionary<Type, Action<IPacket>>(new Dictionary<Type, Action<IPacket>>());

    public static void RegisterPacket<T>(Action<T> handler)
        where T: IPacket
    {
        _Handlers[typeof (T)] = packet => handler((T) packet);
    }

    private void ProcessReceivedPacket(IPacket packet)
    {
        Action<IPacket> handler;
        if (!_Handlers.TryGetValue(packet.GetType(), out handler))
        {
            // Error handling here. No packet handler exists for this type of packet.
            return;
        }
        handler(packet);
    }
}

class Program
{
    private static PacketService _PacketService = new PacketService();
    static void Main(string[] args)
    {
        PacketService.RegisterPacket<FooPacket>(HandleFooPacket);
    }

    public static void HandleFooPacket(FooPacket packet)
    {
        // Do something with the packet
    }
}
Run Code Online (Sandbox Code Playgroud)

您创建的每种类型的包都会注册一个特定于该类型数据包的处理程序.使用ConcurrentDictionary使锁定变得多余.