Compare commits

..
4 Commits
Author SHA1 Message Date
Mo Firouz 1aa70a0d96 Nakama Java 2.5.3 release. 2024-12-02 09:51:53 +00:00
Mo Firouz 818349c8da Add option to specify OkHttp dispatcher for socket connectivity. (#85) 2024-11-30 15:16:19 +00:00
Mo Firouz eb55222866 Nakama Java 2.5.2 release. 2024-10-27 10:26:26 +00:00
Mo Firouz afc257b7b6 Add overloaded methods for async disconnect methods. (#83)
* Add overloaded methods for async disconnect methods.

* Keep socket reference until OnClose is invoked

* Correct session logout. Shutdown executor correctly.

* WebSocket client resources are released immediately after disconnection and are made ready again in case of reconnection.
2024-10-27 10:25:08 +00:00
15 changed files with 217 additions and 32 deletions

No files matched your search

+16
View File
@@ -4,6 +4,22 @@ All notable changes to this project are documented below.
The format is based on [keep a changelog](http://keepachangelog.com/) and this project uses [semantic versioning](http://semver.org/).
## [2.5.3] - 2024-12-02
### Added
- Add option to specify own dispatcher for socket connectivity.
## [2.5.2] - 2024-10-27
### Changed
- WebSocketClient now closes the thread executor service if internal executor was used once the socket is closed.
- Improve client and socket disconnection process.
### Fixed
- Corrected Channel Type enum values to match the protocol.
- Session logout function no longer attempts to renew the token after logout.
- WebSocket client resources are released immediately after disconnection and are made ready again in case of reconnection.
## [2.5.1] - 2024-10-16
### Changed
+1 -1
View File
@@ -42,7 +42,7 @@ lombok {
}
group = 'com.github.heroiclabs'
version = '2.5.1'
version = '2.5.3'
sourceCompatibility = 1.8
targetCompatibility = 1.8
@@ -23,17 +23,17 @@ public enum ChannelType {
/**
* A chat room which can be created dynamically with a name.
*/
ROOM(0),
ROOM(1),
/**
* A private chat between two users.
*/
DIRECT_MESSAGE(1),
DIRECT_MESSAGE(2),
/**
* A chat within a group on the server.
*/
GROUP(2);
GROUP(3);
private final int value;
ChannelType(int value) {
@@ -37,6 +37,8 @@ public interface Client {
/**
* Disconnects the client. This function kills all outgoing exchanges immediately without waiting.
* @deprecated
* This method is deprecated. <p> Use {@link Client#disconnect(long, TimeUnit)} instead.
*/
void disconnect();
@@ -111,6 +113,21 @@ public interface Client {
*/
SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs, final int socketPingMs, ExecutorService listenerThreadExec);
/**
* Create a new socket from the client.
* @param host The host URL of the server.
* @param port The port number of the server. Default should be 7350.
* @param ssl Whether to use SSL to connect to the server.
* @param socketTimeoutMs Sets the connect, read and write timeout for new connections.
* @param socketPingMs The interval at which to send Ping frames to the server.
* @param listenerThreadExec The threading model to use when processing socket messages from the server.
* @param socketThreadExec The threading model to use when processing socket connectivity. See documentation here for more details:
* @see okhttp3.Dispatcher
* @param maxNumConcurrentRequests The maximum number of requests to execute concurrently. Above this requests queue in memory, waiting for the running calls to complete. The okHttpThreadExec must be able to run this number of concurrent requests at the same time.
* @return a new SocketClient instance.
*/
SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs, final int socketPingMs, ExecutorService listenerThreadExec, ExecutorService socketThreadExec, int maxNumConcurrentRequests);
/**
* Add one or more friends by id.
* @param session The session of the user.
@@ -210,22 +210,22 @@ public class DefaultClient implements Client {
@Override
public SocketClient createSocket(final int port, final int socketTimeoutMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl) {
return new WebSocketClient(host, port, ssl, WebSocketClient.DEFAULT_TIMEOUT_MS, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, WebSocketClient.DEFAULT_TIMEOUT_MS, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, WebSocketClient.DEFAULT_PING_MS, this.trace, null);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs, final int socketPingMs) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, Executors.newSingleThreadExecutor());
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, null);
}
@Override
@@ -233,6 +233,11 @@ public class DefaultClient implements Client {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, listenerThreadExec);
}
@Override
public SocketClient createSocket(final String host, final int port, final boolean ssl, final int socketTimeoutMs, final int socketPingMs, ExecutorService listenerThreadExec, ExecutorService socketThreadExec, int maxNumConcurrentRequests) {
return new WebSocketClient(host, port, ssl, socketTimeoutMs, socketPingMs, this.trace, listenerThreadExec, socketThreadExec, maxNumConcurrentRequests);
}
@Override
public ListenableFuture<Empty> addFriends(@NonNull final Session session, @NonNull final String... ids) {
return autoRefreshSession(session, getStub(session).addFriends(AddFriendsRequest.newBuilder().addAllIds(Arrays.asList(ids)).build()));
@@ -1791,7 +1796,7 @@ public class DefaultClient implements Client {
@Override
public ListenableFuture<Empty> logoutSession(@NonNull final Session session) {
return autoRefreshSession(session, getStub(session).sessionLogout(SessionLogoutRequest.newBuilder().setToken(session.getAuthToken()).setRefreshToken(session.getRefreshToken()).build()));
return getStub(session).sessionLogout(SessionLogoutRequest.newBuilder().setToken(session.getAuthToken()).setRefreshToken(session.getRefreshToken()).build());
}
@Override
@@ -24,6 +24,7 @@ import lombok.NonNull;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* A socket connection to the server.
@@ -48,11 +49,18 @@ public interface SocketClient {
/**
* Close the connection with the server.
* @deprecated
* This method is deprecated. <p> Use {@link SocketClient#disconnectSocket()} instead.
*
* @return A close future.
*/
ListenableFuture<Boolean> disconnect();
/**
* Close the connection with the server. This is an asynchronous call, and you should subscribe to OnClose callback to act on this.
*/
void disconnectSocket();
/**
* Join a chat channel on the server.
*
@@ -27,9 +27,6 @@ import com.google.protobuf.Timestamp;
import com.google.type.Date;
import com.heroiclabs.nakama.api.NotificationList;
import com.heroiclabs.nakama.api.Rpc;
import com.heroiclabs.nakama.rtapi.PartyJoin;
import com.heroiclabs.nakama.rtapi.PartyJoinRequestList;
import com.heroiclabs.nakama.rtapi.PartyMatchmakerAdd;
import com.heroiclabs.nakama.rtapi.PartyMatchmakerTicket;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@@ -43,6 +40,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
@@ -77,26 +75,47 @@ public class WebSocketClient implements SocketClient {
private final int port;
private final boolean ssl;
private final boolean trace;
private final OkHttpClient client;
private final Map<String, SettableFuture<?>> collationIds;
private final OkHttpClient.Builder clientBuilder;
private final boolean shouldShutdownListenerThreadExecService;
private boolean shouldShutdownOkHttpThreadExecService;
private ExecutorService listenerThreadExec;
private WebSocket socket;
private final ExecutorService listenerThreadExec;
WebSocketClient(@NonNull final String host, final int port, final boolean ssl,
final int socketTimeoutMs, final int socketPingMs, final boolean trace, ExecutorService listenerThreadExec) {
final int socketTimeoutMs, final int socketPingMs, final boolean trace,
ExecutorService listenerThreadExec) {
this.host = host;
this.port = port;
this.ssl = ssl;
this.trace = trace;
this.collationIds = new ConcurrentHashMap<>();
this.listenerThreadExec = listenerThreadExec;
if (listenerThreadExec != null) {
this.listenerThreadExec = listenerThreadExec;
this.shouldShutdownListenerThreadExecService = false;
} else {
this.listenerThreadExec = Executors.newSingleThreadExecutor();
this.shouldShutdownListenerThreadExecService = true;
}
client = new OkHttpClient.Builder()
clientBuilder = new OkHttpClient.Builder()
.connectTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.readTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.writeTimeout(socketTimeoutMs, TimeUnit.MILLISECONDS)
.pingInterval(socketPingMs, TimeUnit.SECONDS)
.build();
.pingInterval(socketPingMs, TimeUnit.SECONDS);
this.shouldShutdownOkHttpThreadExecService = true;
clientBuilder.setDispatcher$okhttp(new Dispatcher());
}
WebSocketClient(@NonNull final String host, final int port, final boolean ssl,
final int socketTimeoutMs, final int socketPingMs, final boolean trace,
ExecutorService listenerThreadExec, @NonNull ExecutorService okHttpThreadExec, final int maxNumConcurrentRequests) {
this(host, port, ssl, socketTimeoutMs, socketPingMs, trace, listenerThreadExec);
this.shouldShutdownOkHttpThreadExecService = false;
Dispatcher dispatcher = new Dispatcher(okHttpThreadExec);
dispatcher.setMaxRequests(maxNumConcurrentRequests);
clientBuilder.setDispatcher$okhttp(dispatcher);
}
@Override
@@ -107,7 +126,7 @@ public class WebSocketClient implements SocketClient {
@Override
public ListenableFuture<Session> connect(@NonNull final Session session, @NonNull final SocketListener listener, final boolean createStatus) {
if (socket != null) {
return Futures.immediateFailedFuture(new DefaultError("Client is already connected"));
return Futures.immediateFailedFuture(new DefaultError("Socket is already connected"));
}
final String url = new HttpUrl.Builder()
@@ -133,8 +152,24 @@ public class WebSocketClient implements SocketClient {
}
private ListenableFuture<Session> createWebsocket(@NonNull final Session session, @NonNull final SocketListener listener, @NonNull final Request request) {
if (this.listenerThreadExec == null || this.listenerThreadExec.isShutdown()) {
// in case of previously closed/failed socket.
this.listenerThreadExec = Executors.newSingleThreadExecutor();
}
final SettableFuture<Session> connectFuture = SettableFuture.create();
if (clientBuilder.getDispatcher$okhttp().executorService().isShutdown()) {
if (this.shouldShutdownOkHttpThreadExecService) {
// in case we are managing the OkHttpExecService, and it was previously shutdown, then recreate it before creating the client.
clientBuilder.setDispatcher$okhttp(new Dispatcher());
} else {
connectFuture.setException(new Throwable("websocket dispatcher thread executing has been previously shutdown."));
return connectFuture;
}
}
final Object lock = this;
final OkHttpClient client = clientBuilder.build();
socket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(final WebSocket webSocket, final Response response) {
@@ -146,7 +181,7 @@ public class WebSocketClient implements SocketClient {
@Override
public void onMessage(final WebSocket webSocket, final ByteString bytes) {
super.onMessage(webSocket, bytes);
// No text messages are expected.
// No binary messages are expected.
log.warn("Unexpected binary message from server: " + bytes.base64());
}
@@ -293,32 +328,54 @@ public class WebSocketClient implements SocketClient {
@Override
public void onClosed(final WebSocket webSocket, final int code, final String reason) {
super.onClosed(webSocket, code, reason);
listener.onDisconnect(null);
// Graceful socket disconnect is complete, clean up.
synchronized (lock) {
socket.cancel();
socket = null;
collationIds.clear();
if (!connectFuture.isCancelled() && !connectFuture.isDone()) {
connectFuture.setException(new Throwable("Socket closed."));
}
if (shouldShutdownListenerThreadExecService) {
listenerThreadExec.shutdown();
}
// clean up OkHttp Websocket resources.
client.connectionPool().evictAll();
if (shouldShutdownOkHttpThreadExecService) {
client.dispatcher().executorService().shutdown();
}
}
listener.onDisconnect(null);
}
@Override
public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
super.onFailure(webSocket, t, response);
listener.onDisconnect(t);
// Socket has failed and is no longer connected, clean up.
synchronized (lock) {
socket.cancel();
socket = null;
collationIds.clear();
if (!connectFuture.isCancelled() && !connectFuture.isDone()) {
connectFuture.setException(t);
}
}
listener.onDisconnect(t);
if (shouldShutdownListenerThreadExecService) {
listenerThreadExec.shutdown();
}
// clean up OkHttp Websocket resources.
client.connectionPool().evictAll();
if (shouldShutdownOkHttpThreadExecService) {
client.dispatcher().executorService().shutdown();
}
}
}
});
return connectFuture;
@@ -330,12 +387,23 @@ public class WebSocketClient implements SocketClient {
// Returns true if a shutdown was initiated, false if already shutting down or disconnected.
// Either result is acceptable here.
// Socket reference will be set to null when disconnect is completed.
// Don't nullify the socket at this stage as we'll need to have the OnClose called.
socket.close(1000, null);
socket = null;
}
return Futures.immediateFuture(true);
}
@Override
public synchronized void disconnectSocket() {
if (socket != null) {
// Returns true if a shutdown was initiated, false if already shutting down or disconnected.
// Either result is acceptable here.
// Socket reference will be set to null when disconnect is completed.
// Don't nullify the socket at this stage as we'll need to have the OnClose called.
socket.close(1000, null);
}
}
@Override
public ListenableFuture<Channel> joinChat(@NonNull final String target, @NonNull final ChannelType type) {
final ChannelJoinMessage msg = new ChannelJoinMessage(target, type.getValue());
@@ -42,7 +42,7 @@ public class ChannelTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -56,7 +56,7 @@ public class ChannelTest {
Assert.assertNotNull(channel.getSelf());
Assert.assertEquals(session.getUserId(), channel.getSelf().getUserId());
socket.leaveChat(channel.getId()).get();
socket.disconnect();
socket.disconnectSocket();
}
@Test
@@ -43,7 +43,7 @@ public class MatchTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -45,6 +45,8 @@ public class MatchmakerTest {
@After
public void shutdown() throws Exception {
socket.disconnectSocket();
socket2.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -45,7 +45,7 @@ public class NotificationTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -40,7 +40,7 @@ public class RpcTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}
@@ -22,6 +22,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -54,5 +55,13 @@ public class SessionTest {
Assert.assertNotEquals(0, session.getCreateTime());
Assert.assertNotEquals(0, session.getExpireTime());
// let's make sure that we terminate all threads correctly.
for (Thread thread: Thread.getAllStackTraces().keySet()) {
// System.out.printf("%s: %s %s\n", thread.getName(), thread.getState(), thread.isDaemon() ? "(daemon)" : "");
if (!thread.getName().equalsIgnoreCase("main")) {
Assert.assertTrue(thread.isDaemon());
}
}
}
}
@@ -16,12 +16,17 @@
package com.heroiclabs.nakama;
import com.heroiclabs.nakama.api.ChannelMessage;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@@ -42,7 +47,7 @@ public class SocketTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
}
@Test(expected = Error.class)
@@ -112,4 +117,59 @@ public class SocketTest {
Assert.assertTrue("Success callback was not dispatched.", connectCallback.successDispatched);
}
@Test
public void testMultiConnectAndThreadCount() throws Exception {
final List<Boolean> callbacks = new ArrayList<Boolean>();
final CountDownLatch latch = new CountDownLatch(4);
final String content = "{\"message\":\"Hello world\"}";
socket.connect(session, new AbstractSocketListener() {
@Override public void onDisconnect(final Throwable t) {
callbacks.add(true);
latch.countDown();
}
});
socket.disconnectSocket();
Thread.sleep(1000);
socket.connect(session, new AbstractSocketListener() {
@Override
public void onChannelMessage(final ChannelMessage message) {
super.onChannelMessage(message);
callbacks.add(true);
latch.countDown();
}
@Override
public void onChannelPresence(final ChannelPresenceEvent presence) {
super.onChannelPresence(presence);
callbacks.add(true);
latch.countDown();
}
@Override public void onDisconnect(final Throwable t) {
callbacks.add(true);
latch.countDown();
}
});
final Channel channel = socket.joinChat("myroom2", ChannelType.ROOM).get();
Assert.assertNotNull(channel);
final ChannelMessageAck ack = socket.writeChatMessage(channel.getId(), content).get();
Assert.assertNotNull(ack);
socket.disconnectSocket();
Thread.sleep(1000);
latch.await(10, TimeUnit.SECONDS);
// let's make sure that we terminate all threads correctly.
for (Thread thread: Thread.getAllStackTraces().keySet()) {
// System.out.printf("%s: %s %s\n", thread.getName(), thread.getState(), thread.isDaemon() ? "(daemon)" : "");
if (!thread.getName().equalsIgnoreCase("main")) {
Assert.assertTrue(thread.isDaemon());
}
}
Assert.assertEquals(4, callbacks.size());
}
}
@@ -41,7 +41,7 @@ public class StreamTest {
@After
public void shutdown() throws Exception {
socket.disconnect();
socket.disconnectSocket();
client.disconnect(5000, TimeUnit.MILLISECONDS);
}