Important Notes
WebSockets is a cool technology and it opens new doors to ways you can manage your web UI. That said there are some important things that must be taken into consideration while using it. We have already mentioned that WebSockets is used to create a messaging system in uniGUI. This messaging system can be used to deliver messages instantly to all existing clients and force them to update their UI. There are things that must be kept in mind while using WebSockets and the related messaging system.
Business Logic Considerations
When a message is broadcast through the system, the message is received by each client and an Ajax request will be sent by each client to the server to request a UI update. You must make sure that this event handler only contains code that will refresh UI elements. This event handler should not include code which is part of your business logic.
For example, if a database row should be modified as part of your business logic, this should not be done in a form's message event handler (for example, OnBroadcastMessage). It should be done in the event handler which is initiated by the user. Code placed in the OnBroadcastMessage handler should only affect UI elements. All other code which is part of your business logic should only be placed in user event handlers. In short, your application functionality and related business logic should not rely on WebSockets functionality.
Reasons to avoid placing business logic in broadcast handlers:
WebSocket connections may be lost temporarily or may not be available if the browser window is not active or is minimized. In some browsers (notably Google Chrome), WebSocket connections can be put to sleep if the browser tab or window is inactive for a period of time. This means some sessions may temporarily not receive socket messages and therefore won't receive the OnBroadcastMessage event.
When BroadcastMessage is called, the OnBroadcastMessage event will be invoked once per session — meaning the handler may be called multiple times. Any business logic placed there would similarly run multiple times, which is usually unacceptable.
Client Update Considerations
The main principle to follow here is that your updates must be stateless. Each new update should not rely on the previous update. There are cases where a few updates can be missed as a result of connection failure or network instability. Those missed updates should not affect new updates.
There are two events which are fired when a WebSocket connection is established or closed: OnSocketOpen and OnSocketClose. You can use the OnSocketOpen event to detect connection re-establishment. When the connection is re-opened this event is fired and you can fully refresh the UI.
For example, if you update a memo by appending a new line each time a socket message is received, you should fully refresh the memo lines when the OnSocketOpen event is fired so missed messages do not leave the UI in an inconsistent state.