Jump to content

  • Log In with Google      Sign In   
  • Create Account

We need your feedback on a survey! Each completed response supports our community and gives you a chance to win a $25 Amazon gift card!


deadcode

Member Since 20 Jun 2013
Offline Last Active Private

Posts I've Made

In Topic: Handling Messages

20 June 2013 - 08:43 AM

C# reflection based example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Server
{
    //game message
    class Message
    {
        public byte[] Data { get; set; }

        public byte Opcode { get; set; }
    }


    interface IMessageHandler
    {
        void DoMessage(Message message);
    }

    internal class OpcodeAttribute : Attribute
    {
        //or enum
        public byte Opcode { get; set; }

        public OpcodeAttribute(byte opcode)
        {
            Opcode = opcode;
        }
    }

    [Opcode(5)]
    class WalkMessageHandler : IMessageHandler
    {
        public void DoMessage(Message message)
        {
            byte[] bytes = message.Data;
            //todo parse message 
        }
    }


    class MessageHandlerBucket
    {
        private readonly Dictionary<byte,IMessageHandler> _handlers = new Dictionary<byte, IMessageHandler>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="handlersAssembly">all hanlders in one assembly in this case</param>
        public MessageHandlerBucket(Assembly handlersAssembly)
        {
            IEnumerable<Type> types = handlersAssembly.GetTypes().Where(x => x.IsSubclassOf(typeof (IMessageHandler)));
            foreach (var type in types)
            {
                object opcode = type.GetCustomAttributes(typeof (OpcodeAttribute), true).FirstOrDefault();
                if (opcode == null)
                    continue;
                var opcodeAttribute = (OpcodeAttribute) opcode;
                byte code = opcodeAttribute.Opcode;
                var handler = (IMessageHandler) Activator.CreateInstance(type);
                _handlers.Add(code, handler);
            }
        }


        public void Handle(Message message)
        {
            byte opcode = message.Opcode;
            IMessageHandler handler = _handlers[opcode];
            if(handler== null) return;//or throw
            handler.DoMessage(message);
        }
    }
}

PARTNERS