4

Hello swarm intelligence!

Imagine the following:

We've created a rudimentary server / client software to send Events through a local network to invoke Methods in another Program. This is done via an array of Bytes build like: [sender][receiver][messageCode][eventObj(serialized)]

private static byte[] buildByteArray(int Receiver, int Message, CustomEventArgs e = null)
{
  byte[] sender   = BitConverter.GetBytes(HANDSHAKE);
  byte[] receiver = BitConverter.GetBytes(Receiver);
  byte[] message  = BitConverter.GetBytes(Message);
  byte[] obj      = ParseEventToBinary(e);

  IEnumerable<byte> rv = sender.Concat(receiver).Concat(message).Concat(obj);
  return rv.ToArray();
} 

At the receiving end, we got an Array of Type EventHandler

private static EventHandler<CustomEventArgs>[] EventHandlers = new EventHandler<CustomEventArgs>[2000];

Our problem is, Class A only needs to subscribe to the handler, but Class B shall handle all the events AND trigger them.

Class A:

triggerEvent =  client.getHandler(111);
triggerEvent += eventHandlerMethodeOne;

Class B:

public EventHandler<CustomEventArgs> getHandler(int code)
{
    if (EventHandlers[code] != null)
    {
        return EventHandlers[code];
    }
    else
    {
        EventHandlers[code] += 'eventHandlerMethodeOne';
        return EventHandlers[code];
    }
}

Imagine Class A subscribing to EventHandlers and loading Class B which is conncting to the Server and waiting for input. The following 'messageCode' is the index of the previosly created EventHandler. EventHandlers[messageCode] should now

be equal to triggerEvent += eventHandlerMethodeOne;

int messageCode = msgCode[0] + msgCode[1] + msgCode[2] + msgCode[3];
if (EventHandlers[messageCode] != null)
{
    EventHandler<CustomEventArgs> trigger = EventHandlers[messageCode];
    trigger(null, retreiveData(eventArgs));
}
else
{
    SendErrorResponse(sender, 404, new CustomEventArgs());
}

I hope any of you understands what im trying to say..

Question: What do I have to change that the event gets triggerd?

Thanks for your attention!

Edit: Debugging the Code does not bring anything particular to mind.

de0x95
  • 61
  • 4
  • 1
    Does this maybe answer your question: https://stackoverflow.com/questions/987050/array-of-events-in-c? –  Jun 19 '20 at 10:34
  • 1
    @Knoop Sadly no.. Think of the Array as follows: We got 3 EventHandlers and each of those got different Methods attached to it. If Program A needs the methods of the first one, it sends a 0 through the network and it should trigger eventHandlers[0](null, e); – de0x95 Jun 19 '20 at 10:42
  • 1
    Yes so on the receiving end you want an array of eventhandlers triggerable and subscribable by index, which to me looks exactly the same as the referred question (including an answer that makes this work with your `+=` syntax) –  Jun 19 '20 at 10:48
  • 1
    This actually seems pretty legit. I'll try it out and post an edit if it works! – de0x95 Jun 19 '20 at 10:54

0 Answers0