Understanding STATE
STATE is important in real-time applications. Since we have a full-duplex connection there is no need sending information about the connection with every message. Doing so will make messages larger and business logic more complex.
Example 1 - A chat
A chat is often used to demo real-time applications over the web. Even though it is a lame example it makes sense to demo this since building a chat without real-time has some challenges. With real-time it is super easy!
In the chat you user probably signs in or at-least provide a user name. Since we know something like the user name and have a full-duplex connection we only have to tell the server our name once.
When using the chat the client only have to send in the message. The server can then extend the message by adding the user name (known on the server). This way we send less data.
Example 2 - A chat with rooms
Let's say that we have our chat from example 1. Now we want to offer the possibility to have chat rooms. Our users may now be in several rooms at once. This can also be solved with STATE. If you have a property on the controller that stores the current rooms for a user. Something like...
public IList<string> Rooms{get;set;}
...your clients can join/leave rooms and you just update the Rooms
property.
But how can you target the correct room when sending a message? There are many ways to do this, but one simple way is to just pass in the room name with the message. If we know the room we can target all clients in that room very easily.
We just use the InvokeTo<T>(Func<T,bool> exp, object message, string topic);
.
- The first parameter finds all clients to send to. In this case all clients that has the room in the list (using STATE).
- The second parameter just builds a object to send (chat message) combining STATE and incoming data.
- The third parameter is the topic for the message.
this.InvokeTo<Chat>(p => p.Rooms.Contains(m.Room), new {From=this.Name, Room=m.Room, Text=m.Message},"say");