Events are Neoroute’s primary way to send information from the server to the client. And the adapter is the thing you can send to.
Before creating or sending any events, you first need to register them with Neoroute. We need this to couple event names and the structs you use for them.
To do this, create a new EventRegistry like this:
var EventRegistry = neoroute.NewEventRegistry()
You can then add new events to it like this:
//go:generate msgp
type SomeEvent struct { /* your data */ }
var CreateSomeEvent = EventRegistry.Register[SomeEvent]("some_event")
To explain this a little further:
//go:generate msgp is needed to generate the definitions for MessagePack.SomeEvent is the struct that’s gonna be arriving on the client.Register function returns a creation function for the event, that way you don’t have to type the event name, in this case some_event, every time you want to send it.To make it easier for you to keep track of connections, we use what we call adapters. They are simply a wrapper around a connection to any transporter and are used to send events to clients.
To actually be able to send though, you’re going to first need a registry for all of your adapters:
var AdapterRegistry = neoroute.NewAdapterRegistry()
Now, how do you get an adapter? Well, you simply get one from a session (the object you for example get in routes) and register it on the AdapterRegistry:
// session can for example be gotten from a route context with ctx.Session()
adapter, err := session.Adapt()
if err != nil {
panic(err) // TODO: Handle this properly
}
AdapterRegistry.Register("some-identifier", adapter)
Just so it doesn’t cause confusion: some-identifier is the identifier for the adapter. Only one adapter per identifier can exist.
AdapterRegistry.Send("some-identifier", CreateSomeEvent(SomeEvent{ /* ... */ }))AdapterRegistry.Broadcast(CreateSomeEvent(SomeEvent{ /* ... */ }))AdapterRegistry.Unregister("some-identifier")AdapterRegistry.UnregisterAll()We also give you the powerful ability to disconnect users straight from adapters. When you call Disconnect or DisconnectAll on AdapterRegistry instead of Unregister or UnregisterAll, the adapters will be unregistered and the user(s) will be disconnected.
AdapterRegistry objects. If you have multiple collections of connections that belong together, it’s a common pattern to have one AdapterRegistry per collection containing all of the connections.