Forum C# AddMessageHandler() method on server

AddMessageHandler() method on server

Postby robscherer123 » January 8th, 2019, 6:02 pm

I noticed there is an AddMessageHandler() method for the server code. I've never saw it before in the documentation, so I tried it out and it works as it should. However, I noticed there is no RemoveMessageHandler method? For my case this would be needed, as I have objects listening for certain messages, and the listeners will need to be removed once the objects are no longer used. Was this feature never fully completed or something? Could be useful to have.
Paid Member
Posts: 312
Joined: December 12th, 2012, 8:46 pm

Re: AddMessageHandler() method on server

Postby Henrik » January 15th, 2019, 6:44 am

That method looks like an afterthought that was added and forgotten, because all of our documentation is basically about handling everything inside GotMessage.

That said, I'm pretty sure you can write your own one. Inside your Game class:

Code: Select all
private Dictionary<string, List<Action<Player, Message>>> handlers = new Dictionary<string, List<Action<Player, Message>>>();
public void AddHandler(string type, Action<Player, Message> action) {
   if (!handlers.ContainsKey(type)) { handlers[type] = new List<Action<Player, Message>>(); }
public void RemoveHandler(string type, Action<Player, Message> action) {
   if (handlers.ContainsKey(type)) {

public override void GotMessage(Player player, Message message) {
   if (handlers.ContainsKey(message.Type)) {
      foreach (var action in handlers[message.Type]) {
         action(player, message);

        //...the rest of your original GotMessage continues here...

I did a super quick test of this code, and it seems like it should work, but I've probably forgotten something stupid. :-)
Posts: 1877
Joined: January 4th, 2010, 1:53 pm

Return to C#