Step 1. Add the JitPack repository to your build file
Add it in your root settings.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
Add it in your settings.gradle.kts at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
Add to pom.xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.XDex:socketcluster-client-java:2.0.3'
}
dependencies {
implementation("com.github.XDex:socketcluster-client-java:2.0.3")
}
<dependency>
<groupId>com.github.XDex</groupId>
<artifactId>socketcluster-client-java</artifactId>
<version>2.0.3</version>
</dependency>
libraryDependencies += "com.github.XDex" % "socketcluster-client-java" % "2.0.3"
:dependencies [[com.github.XDex/socketcluster-client-java "2.0.3"]]
This SocketCluster Java/Android Client fork has the following differences from upstream:
JsonNode
types, instead of upstream's Object
Important Note: Due to using jackson-databind
this library is significantly bigger in size than upstream (~1.8 Mb), so if binary codec support is not needed, consider using upstream instead.
This client provides following functionality
sc-codec-min-bin
included out-of-the-box)Apache License, Version 2.0
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
...
dependencies {
implementation 'com.github.XDex:socketcluster-client-java:2.0.3'
}
Create instance of Socket
class by passing url of socketcluster-server end-point
//Create a socket instance
String url="ws://localhost:8000/socketcluster/";
Socket socket = new Socket(url);
Important Note : Default url to socketcluster end-point is always ws://somedomainname.com/socketcluster/.
Implemented using BasicListener
interface
socket.setListener(new BasicListener() {
public void onConnected(Socket socket, Map<String, List<String>> headers) {
System.out.println("Connected to endpoint");
}
public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) {
System.out.println("Disconnected from end-point");
}
public void onConnectError(Socket socket, WebSocketException exception) {
System.out.println("Got connect error "+ exception);
}
public void onSetAuthToken(String token, Socket socket) {
System.out.println("Token is "+ token);
}
public void onAuthentication(Socket socket, Boolean status) {
if (status) {
System.out.println("socket is authenticated");
} else {
System.out.println("Authentication is required (optional)");
}
}
});
// This will send websocket handshake request to socketcluster-server
socket.connect();
// This will send websocket handshake request to socketcluster-server
socket.connectAsync();
// This will set automatic reconnection to server with delay of 2 seconds and repeating it for 30 times
socket.setReconnection(new ReconnectStrategy().setDelay(2000).setMaxAttempts(30));
socket.connect();
socket.setReconnection(null);
socket.disableLogging();
socket.emit(eventname, message);
// socket.emit("chat", "Hi");
socket.emit(eventname, message, new Ack() {
public void call(String eventName, JsonNode error, JsonNode data) {
System.out.println("Got message for :" + eventName + " error is: " + error + " data is:" + data);
}
});
The object received can be String, Boolean, Long or JsonNode.
socket.on(eventname, new Emitter.Listener() {
public void call(String eventName, JsonNode data) {
System.out.println("Got message for: " + eventName + " data is: " + data);
}
});
socket.on(eventname, new Emitter.AckListener() {
public void call(String eventName, JsonNode object, Ack ack) {
System.out.println("Got message: " + object);
// ...
if (error){
ack.call(eventName, error, null);
} else{
ack.call(eventName, null, data);
}
//Both error and data can be sent to server
ack.call(eventName, error, data);
}
});
Custom binary SocketCluster codecs are supported.
Support for sc-codec-min-bin is included out-of-the-box.
To enable a binary codec, just set it as follows on the SocketCluster Socket
:
socket.setCodec(new MinBinCodec());
Custom binary codecs must implement the SocketClusterCodec
interface.
Socket.Channel channel = socket.createChannel(channelName);
// Socket.Channel channel = socket.createChannel("yolo");
/**
* without acknowledgement
*/
channel.subscribe();
/**
* with acknowledgement
*/
channel.subscribe(new Ack() {
public void call(String channelName, JsonNode error, JsonNode data) {
if (error == null) {
System.out.println("Subscribed to channel " + channelName + " successfully");
}
}
});
List <Socket.Channel> channels = socket.getChannels();
Socket.Channel channel = socket.getChannelByName("yolo");
//Returns null if channel of given name is not present
// message can have any data type
/**
* without acknowledgement
*/
channel.publish(message);
/**
* with acknowledgement
*/
channel.publish(message, new Ack() {
public void call(String channelName, JsonNode error, JsonNode data) {
if (error == null) {
System.out.println("Published message to channel " + channelName + " successfully");
}
}
});
channel.onMessage(new Emitter.Listener() {
public void call(String channelName , JsonNode object) {
System.out.println("Got message for channel " + channelName + " data is " + data);
}
});
<!--###### Pub-sub without creating channel-->
/**
* without acknowledgement
*/
channel.unsubscribe();
/**
* with acknowledgement
*/
channel.unsubscribe(new Ack() {
public void call(String channelName, JsonNode error, JsonNode data) {
if (error == null) {
System.out.println("channel unsubscribed successfully");
}
}
});
WebSocketFactory
class is responsible for creating websocket instances and handling settings with server, for more
information visit here
To get instance of WebSocketFactory
class :
WebSocketFactory factory = socket.getFactorySettings();
The following is an example to set a custom SSL context to a WebSocketFactory
instance. (Again, you don't have to call a setSSL*
method if you use the default
SSL configuration.)
// Create a custom SSL context.
SSLContext context = NaiveSSLContext.getInstance("TLS");
// Set the custom SSL context.
factory.setSSLContext(context);
NaiveSSLContext
used in the above example is a factory class to create an SSLContext
which
naively accepts all certificates without verification. It's enough for testing
purposes. When you see an error message "unable to find valid certificate path
to requested target" while testing, try NaiveSSLContext
.
If a WebSocket endpoint needs to be accessed via an HTTP proxy, information
about the proxy server has to be set to a WebSocketFactory
instance before
creating a WebSocket
instance. Proxy settings are represented by
ProxySettings
class. A WebSocketFactory
instance has an associated
ProxySettings
instance and it can be obtained by calling
WebSocketFactory.getProxySettings()
method.
// Get the associated ProxySettings instance.
ProxySettings settings = factory.getProxySettings();
ProxySettings
class has methods to set information about a proxy server such
as setHost
method and setPort
method. The following is an example to set a
secure (https
) proxy server.
// Set a proxy server.
settings.setServer("https://proxy.example.com");
If credentials are required for authentication at a proxy server, setId
method and setPassword
method, or setCredentials
method can be used to set
the credentials. Note that, however, the current implementation supports only
Basic Authentication.
// Set credentials for authentication at a proxy server.
settings.setCredentials(id, password);