-
Notifications
You must be signed in to change notification settings - Fork 0
Getting up and running with long polling
Long polling is a good tecnique for sending live data from the server to the client. However, it may get a little tricky when you have multiple data formats. For instance, ChatJS has three different data formats: One for when the users list change, another for new messages, and a last one for when the other using is typing. How do you make sure that the proper client function is going to be called for that particular data format when it arrives in the client?
To solve the above problem, ChatJS defines two function: $.addLongPollingListener()
and $.startLongPolling()
.
The first one, addLongPollingListener, will define that, for a given data-format, the passed in function must be called. Example
$.addLongPollingListener("chat",
// success
function (event) {
if (event.EventKey == "new-messages")
for (var i = 0; i < event.Data.length; i++)
chat.client.sendMessage(event.Data[i]);
else if (event.EventKey == "user-list")
chat.client.usersListChanged(event.Data);
// other checks
},
// error
function (e) {
// error handling here
}
);
The first parameter is just an identifier so the passed in function will only be called if the server response specifies this context. In this example, the passed in function will only be called if the event coming from the server has the "chat" EventKey
. The reason for this is that, if you had other long polling contexts like client notifications, you wouldn't want to have multiple long polling requests. So you create a single long polling request and pass the context as a parameter.
The second one, startLongPolling
, will actually call an URL and wait for long polling events. Example:
$.startLongPolling('/longpolling/getevents');
When you create an instance of the LongPollingAdapter
to pass into ChatJS, you can specify the end-points in the options object. Example options:
{
sendMessageUrl: '/chat/sendmessage',
sendTypingSignalUrl: '/chat/sendtypingsignal',
getMessageHistoryUrl: '/chat/getmessagehistory',
userInfoUrl: '/chat/getuserinfo',
usersListUrl: '/chat/getuserslist'
}
Related resources: