GithubHelp home page GithubHelp logo

sacoo7 / socketcluster-client-java Goto Github PK

View Code? Open in Web Editor NEW
94.0 7.0 42.0 1.55 MB

Native java and android client for socketcluster framework in node.js

Home Page: http://socketcluster.io/

License: Apache License 2.0

Java 98.95% Shell 1.05%
socketcluster java android-client android-demo

socketcluster-client-java's Introduction

Java and Android Socketcluster Client

Overview

This client provides following functionality

  • Support for emitting and listening to remote events
  • Automatic reconnection
  • Pub/sub
  • Authentication (JWT)

License

Apache License, Version 2.0

Gradle

For java

dependencies {
    compile 'io.github.sac:SocketclusterClientJava:2.0.0'
}

for sample java examples visit Java Demo

For android

compile ('io.github.sac:SocketclusterClientJava:2.0.0'){
        exclude group :'org.json', module: 'json'
}

for sample android demo visit Android Demo

Download

Description

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/.

Registering basic listeners

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)");
                }
            }

        });

Connecting to server

  • For connecting to server:
    //This will send websocket handshake request to socketcluster-server
    socket.connect();
  • For connecting asynchronously to server:
    //This will send websocket handshake request to socketcluster-server
    socket.connectAsync();
  • By default reconnection to server is not enabled , to enable it :
    //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();
  • To disable reconnection :
   socket.setReconnection(null); 
  • By default logging of messages is enabled ,to disable :
   socket.disableLogging();

Emitting and listening to events

Event emitter

  • eventname is name of event and message can be String, boolean, Long or JSON-object
    socket.emit(eventname,message);
    
    //socket.emit("chat","Hi");
  • To send event with acknowledgement
    socket.emit(eventname, message, new Ack() {
                public void call(String eventName,Object error, Object data) {
                    //If error and data is String
                    System.out.println("Got message for :"+eventName+" error is :"+error+" data is :"+data);
                }
        });

Event Listener

  • For listening to events :

The object received can be String, Boolean, Long or JSONObject.

    socket.on(eventname, new Emitter.Listener() {
                public void call(String eventName,Object object) {
                    
                    // Cast object to its proper datatype
                    System.out.println("Got message for :"+eventName+" data is :"+data);
                }
        }); 
  • To send acknowledgement back to server
    socket.on(eventname, new Emitter.AckListener() {
            public void call(String eventName,Object object, Ack ack) {
                
                // Cast object to its proper datatype                     
                System.out.println("Got message :: " + object);
                /...
                    Some logic goes here
                .../
                if (error){
                
                ack.call(eventName,error,null);
                
                }else{
                
                //Data can be of any data type
                
                ack.call(eventName,null,data);
                }
                
                //Both error and data can be sent to server
                
                ack.call(eventName,error,data);
            }
        });
        

Implementing Pub-Sub via channels

Creating channel

  • For creating and subscribing to channels:
    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, Object error, Object data) {
                    if (error == null) {
                        System.out.println("Subscribed to channel "+channelName+" successfully");
                    }
                }
        });
  • For getting list of created channels :
    List <Socket.Channel> channels=socket.getChannels();
  • To get channel by name :
        Socket.Channel channel=socket.getChannelByName("yolo");
        //Returns null if channel of given name is not present
        

Publishing event on channel

  • For publishing event :
       // message can have any data type
    /**
     * without acknowledgement
     */
     channel.publish(message);
     
    /**
     * with acknowledgement
     */
       channel.publish(message, new Ack() {
                public void call(String channelName,Object error, Object data) {
                    if (error == null) {
                        System.out.println("Published message to channel "+channelName+" successfully");
                    }
                }
        });
        

Listening to channel

  • For listening to channel event :
    channel.onMessage(new Emitter.Listener() {
             public void call(String channelName , Object object) {
                
                 System.out.println("Got message for channel "+channelName+" data is "+data);
                 
             }
         });

Un-subscribing to channel

    /**
     * without acknowledgement
     */
     
     channel.unsubscribe();
     
    /**
     * with acknowledgement
     */
     
    channel.unsubscribe(new Ack() {
                public void call(String channelName, Object error, Object data) {
                    if (error == null) {
                        System.out.println("channel unsubscribed successfully");
                    }
                }
        });    

Handling logging

  • Once logger object is received, it is very easy to set internal logging level of library, applying handler for each log messages.
  • It can be received using following code
    Logger logger = socket.getLogger();

Handling SSL connection with server

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.

Setting HTTP proxy with server

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);

Star the repo. if you love the client :).

socketcluster-client-java's People

Contributors

aliiizzz avatar angelix avatar mukund2900 avatar sachinsh76 avatar sacoo7 avatar xdex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

socketcluster-client-java's Issues

SocketCluster does not receive messages sent to channel

Hi. I am using OkHttp branch of SocketCluser. I have faced some very strange issue. I am launching Socket. In io.github.sac.BasicListener callback I am able to see that my connection is established and it is successful. The I am registering channel and subscribing to it. And here comes this issues. I am able to receive only two or three events, that were sent to the channel. And after that I am not able to receive any event. I can see that events are sent to the channel from backend but on my Android side they does not come to the channel. I cannot see any logs with errors from socket cluster, and it seems that it is working but for some reasonts doesn't receive any events. The only way to receive these events is to restart the app and connect to channel again. Could you help me please to solve this issue. I can provide my code where I am making connection to Socket

No access to jwt token

Would be nice to include a method for retrieving the AuthToken getAuthToken and even possibly another method for decoding it getSignedToken. Copying methods from here.

Why decode? I send along a list of channels available to a user. Which is used in the Authentication example.

perMessageDeflate no work in Android

// Android works // Web Works
perMessageDeflate: false

// Android does not work // Web works
perMessageDeflate: perMessageDeflate: {
zlibDeflateOptions: {
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
}
}

help

equivalent of send function for sending raw binary data

Is send (or equivalent method) available in android client for sending raw binary data? The web client has socket.send method to send binary data which is available in raw event on server. If not, what is the best way to send raw binary data using android client?

NullPointerException when calling disconnect on socket object with unlimited reconnections

I have initialized the socket and set the reconnection strategy as follows
socket.setReconnection(new ReconnectStrategy());
Now, if I call socket.disconnect() when connection is active, then there is no issue. But if I call the disconnect() method when the connection was broken and reconnection loop is triggered the app is crashing with NullPointerException in reconnect() method.

As I understand the scenario, as soon as connection to the server is broken it initiates a reconnection loop. There is a null check before calling the reconnect() method but no check in the TimerTask. If the disconnect() method is called on the socket object , it will set the strategy to null and when the TimerTask is executed after scheduled time, it is crashing with NullPointerException

I have forked the repo, added a null check in the TimerTask. It is now working without crashing.

NullPointerException - invoking on null object

Platform: Android
Library version:

compile ('io.github.sac:SocketclusterClientJava:1.7.1'){
  exclude group :'org.json', module: 'json'
}

Problem:
On connected, my socket is able to emit and receive messages to and fro the server via internal loggings from the library. However, no callback is actually called to the project's code.

Example:

Android:

socket.setListener(new BasicListener() {
            public void onConnected(Socket socket, Map<String, List<String>> headers) {
                Log.i("Success ", "Connected to endpoint");
                socket.emit("testMessage", "1234");
                socket.on("testMessageBack", new Emitter.AckListener() {
                    @Override
                    public void call(String name, Object data, Ack ack) {
                            Log.e("RESULT", data.toString());
                    }
                });
            }

Server:

    socket.on('testMessage', function(data) {
      socket.emit('testMessageBack', {
        message: 'This is an object with a message property'
      });
    });

Android logs:

Message :{"event":"testMessageBack","data":{"message":"This is an object with a message property"}}
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at io.github.sac.Socket$1.onFrame(Socket.java:185)
at com.neovisionaries.ws.client.ListenerManager.callOnFrame(ListenerManager.java:240)
at com.neovisionaries.ws.client.ReadingThread.callOnFrame(ReadingThread.java:163)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:739)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:110)
at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:66)

It managed to log the results from the server, but my guess is that it's unable to parse them due to some missing data.

Thanks in advance!

I am still receiving data after I stop the service of socket cluster

I have socket cluster client setup as described in the documents. I start the service to listen the changes and stop it when I dont want to listen. My issue is after stopping the service as well I receive data. Either there is another way to stop listening or there is a bug in the library. I have posted the code here.

class SocketForSecurityAgents : IntentService(SocketForSecurityAgents::javaClass.name), BasicListener, AnkoLogger {

  override fun onCreate() {
    super.onCreate()
    info { "onCreate:" }
   
  }

override fun onHandleIntent(intent: Intent?) {
    info { "onHandleIntent socket: ${SERVER_URL + cobaltStore?.token}" }
    val socket = Socket(SERVER_URL + cobaltStore?.token)
    socket.setListener(this)
    socket.setReconnection(ReconnectStrategy().setDelay(2000).setMaxAttempts(30))
    socket.connect()

    channel = socket.createChannel(channelName)
    channel?.subscribe { name, error, data ->
        info { "Subscribe: name: $name" }
        info { "Subscribe: error: $error" }
        info { "Subscribe: data: $data" }
    }
    channel?.onMessage { name, data ->
        info { "name: $name" }
        info { "data: $data" }
   }
}
  override fun onDestroy() {
    super.onDestroy()
    info { "onDestroy" }
  }
}

In my fragmnet I start and stop this service like this.

context.startService(Intent(context, SocketForSecurityAgents::class.java)

context.stopService(Intent(context, SocketForSecurityAgents::class.java)

When service is running to listen from socket, it gives onCreate logs on starting, logs in between in onHandleInten method also I see onDestroy when I stop the service.

My issue is I still receive messages in onHandleIntent after destroying service. Please let me know how to stop listening to channel. These are the logs

2019-03-07 16:40:25.702 22928-22928/myApp I/SocketForSecurityAgents: onCreate:
        2019-03-07 16:40:25.703 22928-22928/myApp I/SocketForSecurityAgents: onCreate: channel localhost_SECURITY
        2019-03-07 16:40:25.724 22928-24605/myApp I/SocketForSecurityAgents: onHandleIntent sconnected tochannel 
        .
        . getting data as expected 
        .
        2019-03-07 16:40:26.024 22928-24607/myApp I/SocketForSecurityAgents: onConnected: socket io.github.sac.Socket@f5a82f6
    2019-03-07 16:40:26.049 22928-22928/myApp I/SocketForSecurityAgents: onDestroy
    2019-03-07 16:40:26.064 22928-24607/myApp I/SocketForSecurityAgents: Subscribe: still receiving
    2019-03-07 16:40:26.064 22928-24607/myApp I/SocketForSecurityAgents: Subscribe: 
    2019-03-07 16:40:26.065 22928-24607/myApp I/SocketForSecurityAgents: Subscribe: 
    2019-03-07 16:40:26.067 22928-24607/myApp I/SocketForSecurityAgents: onAuthentication: status: false
    2019-03-07 16:41:20.161 22928-23872/myApp I/SocketForSecurityAgents: name: .
    2019-03-07 16:41:20.161 22928-23912/myApp I/SocketForSecurityAgents: name: ... still receiving data
    2019-03-07 16:41:20.161 22928-24199/myApp I/SocketForSecurityAgents: name:
    2019-03-07 16:41:20.162 22928-24199/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.162 22928-23912/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.162 22928-23872/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.163 22928-24607/myApp I/SocketForSecurityAgents: name: 
    2019-03-07 16:41:20.163 22928-24607/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.410 22928-23872/myApp I/SocketForSecurityAgents: name: 
    2019-03-07 16:41:20.410 22928-23872/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.413 22928-24199/myApp I/SocketForSecurityAgents: name: 
    2019-03-07 16:41:20.413 22928-24607/myApp I/SocketForSecurityAgents: name: 
    2019-03-07 16:41:20.413 22928-24199/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.413 22928-24607/myApp I/SocketForSecurityAgents: data: 
    2019-03-07 16:41:20.420 22928-23912/myApp I/SocketForSecurityAgents: name: 
    2019-03-07 16:41:20.420 22928-23912/myApp I/SocketForSecurityAgents: data: 

Upgrade Neovisionaries socket library

Currently the library is using a nv-socket lib version that's 8 version behind the latest one.
This means the library is missing (important) features such as SNI support which is currently causing me a lot of issues on an app supporting older Android APIs.

Please upgrade the lib to use a more recent version of the Neovisionaries socket library.

size objects

large objects do not arrive in response

socket.emit("Sala_proba", parameter, new Ack() {
@OverRide
public void call(String name, Object data, Object error) {
Log.i(TAG, "call: name:"+name+",data"+data.toString()+",error:"+error);
//data no work
}
});

connect with auth - error

try connect with apikey and apisecret to wss://sc-02.coinigy.com/socketcluster/.
in Socket.java change connection code -

            `JSONObject handshakeObject=new JSONObject();
            handshakeObject.put("event","#handshake");

            JSONObject obj = new JSONObject();
            obj.put("apiKey", "api");
            obj.put("apiSecret", "secret");

            JSONObject object=new JSONObject();
            object.put("authToken",obj.toString());
            handshakeObject.put("data",object);
            handshakeObject.put("cid",counter.getAndIncrement());
            websocket.sendText(handshakeObject.toString());`

and return - {"authError":{"name":"AuthTokenInvalidError","message":"jwt malformed"},"pingTimeout":20000,"id":"v45cx9vKX-xQXD1BAGmo","isAuthenticated":false}
as i understand - it because the authtoken dont encode by jwt, can u provide the sample of working code with api auth?

Socket .connect function is hard coded to connect to ws://localhost:8000/socketcluster/

Hello,

In your Socket.class, line 347, you have hard coded the class to connect to ws://localhost:8000/socketcluster/ and you're totally ignoring the url which is input in the Socket constructor new Socket(url).

public void connect() { try { this.ws = this.factory.createSocket("ws://localhost:8000/socketcluster/"); } catch (IOException var10) { System.out.printf(var10.getMessage(), new Object[0]); }

Please fix

Subscribe

Need to pass the arguments to subscribe as an issue of security.

AndroidRuntime: FATAL EXCEPTION

My connection with SC getting disconnected sometimes and when i try to send some msg app crashes with below error can you please help me here.

shutting down VM
11–13 09:20:56.221 3371–3371/git.cluster.io.socketclusterandroid E/AndroidRuntime: FATAL EXCEPTION: main
Process: git.cluster.io.socketclusterandroid, PID: 3371
java.lang.NullPointerException: Attempt to invoke virtual method ‘void io.github.sac.Socket$Channel.publish(java.lang.Object)’ on a null object reference
at git.cluster.io.socketclusterandroid.MainActivity$5.onClick(MainActivity.java:146)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.Act

Can't auth by api/secret keys (Java app/Android). Key/Secret Pair Failed

Hello. Can't authorize by api keys from Coinigy API (My Account -> Coinigy API - >Generate new key ->v1)

Source in Kotlin (but was on Java too. Same result)

`import com.neovisionaries.ws.client.WebSocketException
import com.neovisionaries.ws.client.WebSocketFrame
import io.github.sac.BasicListener
import io.github.sac.ReconnectStrategy
import io.github.sac.Socket
import org.json.JSONObject

class EntryPoint {
companion object {
@JvmStatic
fun main(args: Array) { //entry point
val entryPoint = EntryPoint()
entryPoint.openSocket()
}
}

private val url = "wss://sc-02.coinigy.com/socketcluster/"
private val apiKey = "8a0ab8baf5cb81b78dc5505027876cce"
private val apiSecret = "bd5a3aead6a2fb10756f099a60823d15"

private val socket = Socket(url)

private fun openSocket() {
    with(socket) {
        setListener(object : BasicListener {
            override fun onAuthentication(socket: Socket?, status: Boolean?) {
                val jsonObject = JSONObject()
                jsonObject.put("apiKey", apiKey)
                jsonObject.put("apiSecret", apiSecret)
                socket?.emit("auth", jsonObject, { name, error, data -> System.out.println("name::$name error::$error data::$data") })
            }

            override fun onConnectError(socket: Socket?, exception: WebSocketException?) =
                    System.out.println("Got connect error $exception")

            override fun onSetAuthToken(token: String?, socket: Socket?) =
                    socket!!.setAuthToken(token)

            override fun onConnected(socket: Socket?, headers: MutableMap<String, MutableList<String>>?) =
                    System.out.println("onConnected to end-point")

            override fun onDisconnected(socket: Socket?, serverCloseFrame: WebSocketFrame?, clientCloseFrame: WebSocketFrame?, closedByServer: Boolean) =
                    System.out.println("Disconnected from end-point")
        })
        setReconnection(ReconnectStrategy().setDelay(3000).setMaxAttempts(30))
        connect()
    }
}

}`

Log output:

onConnected to end-point
May 20, 2018 12:17:26 PM io.github.sac.Socket$1 onFrame
INFO: Message :{"data":{"pingTimeout":20000,"id":"iDJKmOeysy60hZkGABuU","isAuthenticated":false},"rid":1}
May 20, 2018 12:17:26 PM io.github.sac.Socket$1 onFrame
INFO: Message :{"data":"Key/Secret Pair Failed","rid":2,"error":{"errorCode":403,"errorMsg":"Key/Secret Pair Failed"}}
name::auth error::{"errorCode":403,"errorMsg":"Key/Secret Pair Failed"} data::Key/Secret Pair Failed

SocketCluster Android Client Can't Receive message on 'message' event

I have a nodejs server base on SocketCluster.
My issue is: From Android Client (base on https://github.com/sacOO7/socketcluster-client-java),
I can send message to server successfully, but I can’t receive the message from server(socket.send(msgStr))
on message event. Some of android code as follows:
scSocket.on("message", new io.github.sac.Emitter.Listener() {
public void call(String eventName,Object object) {
// Cast object to its proper datatype
System.out.println("Got message for :"+eventName+" data is :"+data);
}
});
Can you give me some suggest, thanks.

Could not HEAD 'https://jitpack.io/io/github/sac/SocketclusterClientJava/1.7.5/SocketclusterClientJava-1.7.5.pom'. Received status code 401 from server: Unauthorized

Facing Unauthorised issue again. Same link asking for credentials too.

NOTE: A very high priority for support of mavenCentral() [ or any other repo provider] require as jcenter() near to shutdown. Already stuck in migrating project due to this lib not migrated to other repo. Please do support this.
Also, Not able to get libs too from provided link.

SocketCluster Android Client can't subscribe message

Excuse me, I have an issue about SC Android client,
When nodejs server publish message by scServer.exchange.publish(’S12’, data)
In Android client, I subscribe the channel ’S12’ as following:
1 scSocket.onSubscribe("S12_2",new Emitter.Listener() {
2 @OverRide
3 public void call(String name, final Object data) {
4 Log.e("# onSubscribe #", "Listen onSubscribe");
5 }
6 });
But I can’t receive the message, the onSubscribe doesn’t be fired at all, following source code
doesn’t fired too.

scSocket.on("S12_2", new Emitter.Listener() {
public void call(String eventName, Object object) {
JSONObject data;
try {
data = new JSONObject((String) object);
Log.e("# Receive #", (String)object);
//channel = data.getString("session");
} catch (JSONException e) {
return;
}
}
});

Can you help me, thank you so much!

auth before connect to socket connection

hi
in socket.io i use this way for auth before connect to socket.

IO.Options options = new IO.Options(); options.query = "token=" + token; socket = IO.socket(SERVER_ADDRESS, options); socket.connect();
can i user this way with this library?

Socket Basic Listener does not receive messages in few phones.

I am using this code to listen to the socket messages from our server.

Issue is I am testing with 2 samsung galaxy S7Edge phones both API level 26 and it one phone the socket messages works and in other phone it does not. Another test phone I am working with is Samsung S5 Neo with API 24 and it works with that phone.

I have looked into the the phones notification settings but it looks good.

Please let me know what phone settings I need to look at or what is the issue in the below code on setting the SocketClusterService.

Library Version: 1.7.5

public class SocketClusterService extends IntentService implements BasicListener {


private static final String SERVER_URL = "url"
Socket socket;
Socket.Channel channel;
EventBus bus = EventBus.getDefault();

public SocketClusterService() {
    super("SocketClusterService");
}
@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "onCreate: socket:");
}

@Override
public void onDestroy() {
    super.onDestroy();
}

// Will be called asynchronously by Android
@Override
protected void onHandleIntent(Intent intent) {
    this.socket = new Socket(SERVER_URL + cobaltStore.getToken());
    socket.setListener(this);

    //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();

    channel = socket.createChannel("channelName");
    channel.subscribe((name, error, data) -> {
        Log.d(TAG, "onHandleIntent: name " + channel.getChannelName());
        Log.d(TAG, "onHandleIntent: error " + error);
        Log.d(TAG, "onHandleIntent: data " + data);
    });

    channel.onMessage((channelName, object) -> {
                 //use object data..!!
    });
}

@Subscribe
public void onEvent(CobaltStore.CobaltStoreChangeEvent event) {

    Log.e(TAG, "EVENT");

    if (channel != null) {
        channel.publish("We come in peace!");
    }
}

@Override
public void onConnected(Socket socket, Map<String, List<String>> headers) {
    Log.e(TAG, "onConnected");
    Log.d(TAG, "onConnected: " + headers);

}

@Override
public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) {
    Log.e(TAG, "onDisconnected");
}

@Override
public void onConnectError(Socket socket, WebSocketException exception) {
    Log.e(TAG, "onConnectError ", exception);
}

@Override
public void onAuthentication(Socket socket, Boolean status) {
    Log.d(TAG, "onAuthentication: status " + status);
}

@Override
public void onSetAuthToken(String token, Socket socket) {  socket.setAuthToken(token);    }

}

Add support for RxJava and asynchronous connect

Implement Observable stream pattern in the library, keep separate subscribers to receive and send data to the server. Add extra methods ( not present currently) that simplify library usage.

Missing artifacts:

'io.github.sac:SocketclusterClientJava:1.7.5' when trying to add the following dependency in maven getting the following error missing artifacts.I am using the Maven without the Spring Dependency.
Whether we should have spring for this dependency?

can we have the plain java client without gradle because i am new to maven and socket programming
the example that is showed in the git consist of only gradle kindly point the link for the java client using maven dependency

Emitter.Listener callback not compiles. Not works.

Hi, I'm creating socket client part, and I have a problem in Emitter.Listener. The listener not throws any exception, it only not compiles. SO when I'm doing debug, and I set breakpoint in that callback, it jumps over the call. I have some pictures where I explain my problem very well.
screen shot 2018-04-13 at 4 17 52 pm
screen shot 2018-04-13 at 4 24 22 pm
screen shot 2018-04-13 at 4 24 53 pm
screen shot 2018-04-13 at 4 53 07 pm
screen shot 2018-04-13 at 4 53 22 pm
Any ideas why it's not working. It connects well, and the state is OPEN, but in that call I have to send my tokens into server.

cannot authenticate wesocket connection from java client

Hi i am trying to get websocket stream using following code

`import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFrame;
import io.github.sac.*;

import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class Main {

public static String url= "wss://sc-02.coinigy.com/socketcluster/";

public static void main(String arg[]) throws JSONException {

	
    Socket socket = new Socket(url);
    JSONObject obj = new JSONObject();
    obj.put("apiKey", "eee");
    obj.put("apiSecret", "xxx");
    socket.setListener(new BasicListener() {

        public void onConnected(Socket socket,Map<String, List<String>> headers) {
            System.out.println("Connected to endpoint");    
            socket.emit("auth", obj.toString(), new Ack() {
                @Override
                public void call(String eventName, Object error, Object data) {
                    System.out.println("Got message for :"+eventName+" error is :"+error+" data is :"+data);
                }
            });
        	
        }

        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("Set auth token got called");
            socket.setAuthToken(token);
        }

        public void onAuthentication(Socket socket,Boolean status) {
        	
            if (status) {
                System.out.println("socket is authenticated");
            } else {
                System.out.println("Authentication is required (optional)");
            }
        }

        
    });


   socket.setReconnection(new ReconnectStrategy().setDelay(3000).setMaxAttempts(10)); //Connect after each 2 seconds for 30 times

    socket.connect();

    Socket.Channel channel = socket.createChannel("RADE-OK--BTC--CNY");
    channel.subscribe(new Ack() {
        @Override
        public void call(String channelName, Object error, Object data) {
            if (error==null){
                System.out.println("Subscribed to channel "+channelName+" successfully");
            }
        }
    });

    channel.onMessage(new Emitter.Listener() {
        @Override
        public void call(String channelName, Object data) {

            System.out.println("Got message for channel "+channelName+" data is "+data);
        }
    });

    channel.unsubscribe(new Ack() {
        @Override
        public void call(String name, Object error, Object data) {
            System.out.println("Unsubscribed successfully");
        }
    });
    channel.unsubscribe();
}

}`

I am emitting the auth msg but still i ma getting the following error:

NFO: Message :{"rid":2,"error":"Your are connected but this socket has not been authenticated. Please emit auth event with credentials payload."}
Dec 26, 2017 3:27:28 AM io.github.sac.Socket$1 onFrame
INFO: Message :{"data":{"pingTimeout":20000,"id":"vXgm9NvKjCcvB6mVACFj","isAuthenticated":false},"rid":1}

Can you please help

Channel.on not works good. What's the problem?

Hi. I have a chat application where I'm using sockets. In this application I'm connecting to socket then I send my tokens into server then I'm creating channel -> subscribing -> listening to this channel with Channel.on . So the problem is that I'm can't to get messages with channel.on sometimes. Example when I'm login in this app I have to get message from server that right now only I'm online in this chat. When I do login, sometimes I get the message from server, but sometimes it don't comes. The backend for web works good, so I think I'm not done something in android. But how can I one time get the message and the second time not get?

Here's the sample code.

private void socketCall() {

    sc = new Socket(url);

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            sc.connect();
        }
    });

    thread.start();

    final Socket.Channel channel = sc.createChannel(myUserName);

    sc.setListener(new BasicListener() {

        public void onConnected(Socket socket, Map<String, List<String>> headers) {
            Log.d(TAG, "Connected to endpoint");

            JSONObject authObject = new JSONObject();

            try {
                authObject.put("accessToken", getAccessToken());
                authObject.put("refreshToken", getRefreshToken());
                sc.emit("auth", authObject);
                channel.subscribe();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            channel.onMessage(new Emitter.Listener() {
                @Override
                public void call(String name, final Object data) {

                    Log.d(TAG, "Got data from server: " + data.toString());

                    try {
                        JSONObject object = new JSONObject(data.toString());
                        String message = object.getString("message");
                        String sender = object.getString("from");

                        Log.d(TAG, "That's your message: " + message);
                        Log.d(TAG, "You got message from user:  " + sender);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) {
            Log.d(TAG, "Disconnected from end-point");
        }

        public void onConnectError(Socket socket, WebSocketException exception) {
            Log.d(TAG, "Got connect error " + exception);
        }

        public void onSetAuthToken(String token, Socket socket) {
            Log.d(TAG, "Set auth token got called. Here is your token: " + token);
        }

        public void onAuthentication(Socket socket, Boolean status) {
            if (status) {
                Log.d(TAG, "socket is authenticated");
            } else {
                Log.d(TAG, "Authentication is required (optional)");
            }
        }
    });
    messageInput.setInputListener(this);
}

@Override
public boolean onSubmit(CharSequence input) {
    if(sc.isconnected() && sc.getChannelByName(myUserName) != null) {
        JSONObject messageObject = new JSONObject();

        try {
            messageObject.put("msg", input.toString());
            messageObject.put("user", messageReceiverUserName);
            sc.emit("messaging", messageObject);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        sc.getChannelByName(myUserName).publish(input.toString(), new Ack() {
            @Override
            public void call(String name, Object error, Object data) {
                Log.d(TAG, "Published message to channel: " + name + " successfully");
            }
        });
    } else {
        Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
    }
    return true;
}

Here's the socket part. I'm creating channel with my username. So where I done something wrong?

@sacOO7 Please help.

Android client Basic listener not working

@sacOO7 Hy, how are you? Can you help me I have one problem. I have a chat application where I'm registering , authorizing, connecting to socket. In basic listener: in onConnected method I'm sending my tokens into server. In onAuthenticated method I'm creating channel, then subscribing it. All works good, but when I'm creating a new account, the basic listener not works. So I'm connecting and then nothing. If I will logout and login again that will work.

So here's the code, I think you understood. If you not, I can explain more and more))

sender = bundle.getString(BUNDLE_USER_NAME); myUserName = SharedPreferencesManager.getInstance().getUserData().getUserName();

I'm creating channel with my userName which is unique. I need other user userName too. I'm getting them successfully.

sc = new Socket(url);`

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "start connecting");
                sc.setReconnection(new ReconnectStrategy().setDelay(2000).setMaxAttempts(10));
                sc.connect();

>  //The problem is here (this listener not works)               


sc.setListener(new BasicListener() {

                    public void onConnected(Socket socket, Map<String, List<String>> headers) {
                        Log.d(TAG, "Connected to endpoint");

                        JSONObject authObject = new JSONObject();

                        try {
                            Log.d(TAG, "authObject");


> //I'm getting tokens successfully too.

                            
                            authObject.put("accessToken", access_token;
                            authObject.put("refreshToken", refresh_token);


>  //Then I'm sending tokens to server        

                   

                   sc.emit("auth", authObject, new Ack() {
                                @Override
                                public void call(String name, Object error, Object data) {
                                    Log.d(TAG, "Ack");
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) {
                        Log.d(TAG, "Disconnected from end-point");
                    }

                    public void onConnectError(Socket socket, WebSocketException exception) {
                        Log.d(TAG, "Got connect error " + exception);
                    }

                    public void onSetAuthToken(String token, Socket socket) {
                        Log.d(TAG, "Set auth token got called. Here is your token: " + token);
                    }

                    public void onAuthentication(Socket socket, Boolean status) {
                        if (status) {
                            Log.d(TAG, "socket is authenticated");
                        } else {
                            Log.d(TAG, "Authentication is required (optional)");
                        }

> //Here I'm create channel with my username, then I'm subscribing to this channel.

                        final Socket.Channel channel = sc.createChannel(myUserName);
                        channel.subscribe();
  

> //Here I'm listening to this channel     

               
                   channel.onMessage(new Emitter.Listener() {
                            @Override
                            public void call(String name, final Object data) {
                                Log.d(TAG, "Got data from server: " + data.toString());
                                JSONObject object = new JSONObject(data.toString());
                                final String message = object.getString("message");
                                sender = object.getString("from");
                               messagesAdapter.addToStart(MessagesFixtures.getTextMessage(message + "  " + sender, "1"), true);
                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            }
        });

        thread.start();

        messageInput.setInputListener(this);

Here is the code. When I'm creating new user and want to chat, the basic listener not works (so it jumps over it in debug mode). After logout and login it works successfull. So is in my code all right, am I done something wrong? Please help @sacOO7 . Thank you.

Unable to connect

Hello,

Here's my SocketCluster Kubernetes app scc.qurba.io

When I connect using your Android client on url "ws://scc.qurba.io/socketcluster/"

I get the following error

01-05 19:23:57.873 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: === Status Line ===
01-05 19:23:57.873 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: HTTP Version =
HTTP/1.1
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Status Code =
404
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Reason Phrase =
Not Found
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: === HTTP Headers ===
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: ConnectionKeep-Alive
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Content-Length27
01-05 19:23:57.874 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Content-Typetext/html; charset=utf-8
01-05 19:23:57.875 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: DateThu, 05 Jan 2017 17:24:09 GMT
01-05 19:23:57.875 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Servernginx/1.11.3
01-05 19:23:57.875 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: Strict-Transport-Securitymax-age=15724800; includeSubDomains; preload
01-05 19:23:57.875 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: X-Content-Type-Optionsnosniff
01-05 19:23:57.875 5249-5396/io.qurba.android.debugtool I/io.github.sac.Socket: X-Powered-ByExpress

If I connect to "ws://scc.qurba.io/", I get the following:

01-05 19:28:21.793 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: === Status Line ===
01-05 19:28:21.793 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: HTTP Version =
HTTP/1.1
01-05 19:28:21.793 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Status Code =
200
01-05 19:28:21.793 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Reason Phrase =
OK
01-05 19:28:21.793 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: === HTTP Headers ===
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Age0
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Cache-Controlpublic, max-age=0
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: ConnectionKeep-Alive
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Content-Encodinggzip
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Content-Typetext/html; charset=UTF-8
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: DateThu, 05 Jan 2017 17:28:33 GMT
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: ETagW/"a73-4172037613"
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Last-ModifiedThu, 05 Jan 2017 16:26:39 GMT
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Servernginx/1.11.3
01-05 19:28:21.794 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Strict-Transport-Securitymax-age=15724800; includeSubDomains; preload
01-05 19:28:21.795 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: Transfer-Encodingchunked
01-05 19:28:21.795 9948-10098/io.qurba.android.debugtool I/io.github.sac.Socket: X-Powered-ByExpress

In both cases, I don't get onConnected triggered nor onConnectError

Socket don't have Receiver like js client

  • On JS client can receiver thru
    (async () => {
    for await (let data of socket.receiver('AAA')) {
    console.log(data);
    }
    })();
    But I can't find a similar function on client JAVA.

Keep getting Error 400 "Reason Phrase = URL not supported" when trying to connect

Hello,

I have my socketcluster built on kubernetes and rancher, here's the link sc.qurba.io

I keep getting error 400 as below:

12-05 00:13:37.931 9852-10020/io.qurba.android.debugtool I/System.out: === Status Line ===
12-05 00:13:37.932 9852-10020/io.qurba.android.debugtool I/System.out: HTTP Version = HTTP/1.1
12-05 00:13:37.932 9852-10020/io.qurba.android.debugtool I/System.out: Status Code = 400
12-05 00:13:37.932 9852-10020/io.qurba.android.debugtool I/System.out: Reason Phrase = URL not supported
12-05 00:13:37.932 9852-10020/io.qurba.android.debugtool I/System.out: === HTTP Headers ===
12-05 00:13:37.932 9852-10020/io.qurba.android.debugtool I/System.out: Connection: close

Here's my code trying to connect

SocketHelper.socket = new Socket("ws://sc.qurba.io/");

I also tried with the below

SocketHelper.socket = new Socket("http://sc.qurba.io/");

WebSocket sendText on a null object reference

Capture

Sorry because of my English
My app was crashed only in the first times install app because of this bug But after that it's run normally
And i don't use com.neovisionaries.ws.client.WebSocket.sendText anywhere
Please help me !

onDisconnect/onError not called

Hi @sacOO7 , I am currently facing the exact issue you reported with neovisionaries. I am using it in Android phones majority of which are on 2G sims. Several times it happens that android doesn't identify the connection is broken(2G symbol available) but the connection with server is broken. It never identifies the connection is broken and never initiates the reconnection loop until the phone is rebooted or the internet connection is gone completely.

Is there any work around at the moment.?

Socket options similar to js client

Docs have not specified how to pass other options, similar to what js client does. The only specified option is url, would like to pass options like below in js client.

var options = {
  path: '/socketcluster/',
  port: 8000,
  hostname: '127.0.0.1',
  autoConnect: true,
  secure: false,
  rejectUnauthorized: false,
  connectTimeout: 10000, //milliseconds
  ackTimeout: 10000, //milliseconds
  channelPrefix: null,
  disconnectOnUnload: true,
  multiplex: true,
  autoReconnectOptions: {
    initialDelay: 10000, //milliseconds
    randomness: 10000, //milliseconds
    multiplier: 1.5, //decimal
    maxDelay: 60000 //milliseconds
  },
  authEngine: null,
  codecEngine: null,
  subscriptionRetryOptions: {},
  query: {
    yourparam: 'hello'
  }
};

Question about Data Synchronisation

hello ,
I wanted to know if there is a mechanism for saving the data of a channel in a relational database (i.e mysql or ...) or non-relational database. in case a client disconnects from a channel does it exist a data synchornisation mechanism so that it receive the data exchanged when it was not connected like a snapshoot ?
I read an article mentioning this Mechnismus (https://blog.baasil.io/socketcluster-design-patterns-for-chat-69e76a4b1966 )... but unfortunately I do not see any API in the documentation on the website .

can connect to wss (SSL) server

Getting this error
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
while connecting to wss server. Can this client handle SSL connections? wss://----/socketcluster

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.