Using long polling to reduce number of calls.
This commit is contained in:
@@ -46,6 +46,18 @@ public class ChatRoomMediator {
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasPendingMessages(String playerId) throws SubscriptionExpiredException {
|
||||
_lock.readLock().lock();
|
||||
try {
|
||||
GatheringChatRoomListener gatheringChatRoomListener = _listeners.get(playerId);
|
||||
if (gatheringChatRoomListener == null)
|
||||
throw new SubscriptionExpiredException();
|
||||
return gatheringChatRoomListener.hasMessages();
|
||||
} finally {
|
||||
_lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public List<ChatMessage> getPendingMessages(String playerId) throws SubscriptionExpiredException {
|
||||
_lock.readLock().lock();
|
||||
try {
|
||||
|
||||
@@ -23,6 +23,10 @@ public class GatheringChatRoomListener implements ChatRoomListener {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public synchronized boolean hasMessages() {
|
||||
return _messages.size()>0;
|
||||
}
|
||||
|
||||
public synchronized Date getLastConsumed() {
|
||||
return _lastConsumed;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import javax.ws.rs.core.Response;
|
||||
|
||||
public abstract class AbstractResource {
|
||||
protected final boolean _test = System.getProperty("test") != null;
|
||||
protected final long _longPollingLength = 5000;
|
||||
protected final long _longPollingInterval = 200;
|
||||
|
||||
@Context
|
||||
protected PlayerDAO _playerDao;
|
||||
|
||||
@@ -84,17 +84,15 @@ public class ChatResource extends AbstractResource {
|
||||
|
||||
try {
|
||||
// Use long polling
|
||||
List<ChatMessage> chatMessages;
|
||||
int retry = 5;
|
||||
do {
|
||||
chatMessages = chatRoom.getPendingMessages(resourceOwner.getName());
|
||||
retry--;
|
||||
long start = System.currentTimeMillis();
|
||||
while (System.currentTimeMillis()<start+_longPollingLength && !chatRoom.hasPendingMessages(resourceOwner.getName())) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
Thread.sleep(_longPollingInterval);
|
||||
} catch (InterruptedException exp) {
|
||||
|
||||
}
|
||||
} while (retry>0 && chatMessages.size() == 0);
|
||||
}
|
||||
List<ChatMessage> chatMessages = chatRoom.getPendingMessages(resourceOwner.getName());
|
||||
|
||||
Collection<String> usersInRoom = chatRoom.getUsersInRoom();
|
||||
|
||||
|
||||
@@ -173,11 +173,10 @@ public class GameResource extends AbstractResource {
|
||||
Element update = doc.createElement("update");
|
||||
|
||||
// Use long polling
|
||||
int retry = 5;
|
||||
while (retry>0 && !gameMediator.hasAnyNewMessages(resourceOwner, channelNumber)) {
|
||||
retry--;
|
||||
long start = System.currentTimeMillis();
|
||||
while (System.currentTimeMillis()< start+_longPollingLength && !gameMediator.hasAnyNewMessages(resourceOwner, channelNumber)) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
Thread.sleep(_longPollingInterval);
|
||||
} catch (InterruptedException exp) {
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user