Maintaining user state
It's very likely that you may want to store some user state associated with each session. In this case, you can safely use instance variables to maintain this state, as each connection creates a unique instance of the endpoint
class.
Moreover, there is an extra associated map with the session
object, where you can store and retrieve user state. Although instance variables will do, the session
object is useful in cases where you need to expose those states to other sessions of the same endpoint. In situations such as chatting, you may loop over all open sessions and examine each session's username, to check whether this message should be delivered to them or not.
Let's look at how can we use this extra map in practice. Suppose we are designing a WebSockets endpoint for a chat room; we will accept connections on /rooms/{roomName}/{username}
. For each new user joining a room, we will send him/her the names of all the users in this room (including themselves). We will extend...