Sails socket.io from Android app - android

I use sails v0.11.2 and try to connect to web sockets with https://github.com/socketio/socket.io-client-java
My problem is when I logout from my server (I use passport.js) the disconnect event was fired correctly but I can't reconnect after this event append.
Here is my code :
socket = IO.socket(Constants.LOCAL_URL + "?__sails_io_sdk_version=0.11.0");
socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
Transport transport = (Transport) args[0];
transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
#SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) args[0];
// modify request headers
headers.put("Cookie", Arrays.asList(COOKIE));
}
});
}
});
socket.on(Socket.EVENT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onError();
}
Log.e("test", "ERROR");
}
}).on(Socket.EVENT_CONNECT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
listener.onConnect();
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
listener.onDisconnect();
}
}).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_RECONNECT_FAILED, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
});
socket.connect();
And here is my listener when I try to reconnect after is disconnect event :
SocketIOManager.SocketConnexionListener socketConnexionListener = new SocketIOManager.SocketConnexionListener()
{
#Override
public void onConnect()
{
Log.e("test", "CONNECT");
}
#Override
public void onError()
{
Log.e("test", "ERROR");
}
#Override
public void onDisconnect()
{
createSocket();//Call the code above to create a new socket or call socket.connect(); but it's not working and no error throw...
Log.e("test", "DISCON");
}
#Override
public void onConnectError()
{
Log.e("test", "CONNECT ERROR");
}
};

Related

Socket.io Emitter.Listener() not working on Android 9 (API level 28)

I am trying to connect Node server Socket From android for Live Order track purpose, I couldn't connect to the server in Version 9 Android devices but works fine in lower versions. I didn't get LatLog From Server, but it is fetching in lower Devices.
I am using FCM as well for Notification purposes.
android:usesCleartextTraffic="true"
The above Manifest line not worked in my case
Kindly find my code below
private void ConnectSocket() {
try {
final JSONObject objInit = new JSONObject();
// objInit.put ("user_joined", bookingKey);
objInit.put("user_joined", bookingKey);
if (socket == null) {
socket = IO.socket(Urls.socketUrl);
} else {
System.out.println("Socket is already connected");
}
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("user_joined", bookingKey);
locationList.clear();
}
}).on("authenticated", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("newlocation", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
})
.on(bookingKey, new Emitter.Listener() {
#Override
public void call(Object... args) {
final String taxiDetails = args[0].toString();
System.out.println("Received from Socket :" + args[0].toString());
try {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject Job_CarDetails = new JSONObject(taxiDetails);
String latitude = Job_CarDetails.getString("latitude");
String longitude = Job_CarDetails.getString("longitude");
if (locationList.size() == 0) {
MarkerOptions mMarkerOptions = new MarkerOptions().position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_van));
Marker mMarker = googleMap.addMarker(mMarkerOptions);
MarkerList markerList = new MarkerList();
markerList.setLatitude(latitude);
markerList.setLongitude(longitude);
markerList.setMarker(mMarker);
locationList.add(markerList);
} else {
LatLng mToPosition = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
if (!socket.connected()) {
try {
socket.connect();
socket.emit("user_joined", bookingKey);
locationList.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
How can I modify my code, to connect version 9 Devices to the server?? Any help would be appreciated.
This issue was not from the Android side, it is on the server-side. This case raised because of local Server pointing when the Server moved to live Server, Socket Connection Worked.
Thanks.

How to connect 3+ devices using Google-Nearby Connection APIs

I am building an app that should connect at least 4 devices using nearby connection api. I am able to connect them intermittently, other wise only two devices are getting connected.
I am using P2P-CLUSTER Topology and sending data as file payloads which are successfully sent.
I have two questions:
Any suggestion on how to have a stable connection among 2+ devices.
While sending data as file payloads, a folder is created in the download folder. Is there any way to discard this step and be able to send data directly as file payloads without having to save them locally.
Here is my code regarding the connection part only.
private final EndpointDiscoveryCallback endpointDiscoveryCallback =
new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(String endpointId, final DiscoveredEndpointInfo info) {
arrlist.add(endpointId);
for (int i = 0; i< arrlist.size(); i++) {
connectionsClient
.requestConnection(Build.MODEL, arrlist.get(i), connectionLifecycleCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
#Override
public void onEndpointLost(#NonNull String endpointId) {
}
};
private final ConnectionLifecycleCallback connectionLifecycleCallback =
new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String endpointId, #NonNull ConnectionInfo connectionInfo) {
// Automatically accept the connection on both sides.
connectionsClient.acceptConnection(endpointId, new PayloadCallback() {
#Override
public void onPayloadReceived(#NonNull String s, #NonNull Payload payload) {
}
}
#Override
public void onPayloadTransferUpdate(#NonNull String s, #NonNull PayloadTransferUpdate payloadTransferUpdate) {
}
#Override
public void onConnectionResult(#NonNull String endpointId, ConnectionResolution result) {
switch (result.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
if(arrlist != null && arrlist.contains(endpointId)){
System.out.println(TAG+ " End Point Found");
} else {
arrlist.add(endpointId);
}
connectionsClient.stopDiscovery();
connectionsClient.stopAdvertising();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
// Some code
break;
case ConnectionsStatusCodes.STATUS_ERROR:
// Some code
break;
default:
}
}
#Override
public void onDisconnected(#NonNull String endpointId) {
// some code
}
};
private void startAdvertising() {
AdvertisingOptions advertisingOptions =
new AdvertisingOptions.Builder().setStrategy(STRATEGY).build();
Nearby.getConnectionsClient(context)
.startAdvertising(
android.os.Build.MODEL, getPackageName(), connectionLifecycleCallback, advertisingOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
private void startDiscovery() {
DiscoveryOptions discoveryOptions =
new DiscoveryOptions.Builder().setStrategy(STRATEGY).build();
Nearby.getConnectionsClient(context)
.startDiscovery(getPackageName(), endpointDiscoveryCallback, discoveryOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}

Connect to several Mqtt servers using paho.mqtt.android

Can this library give opportunity make connections for several servers?
https://github.com/eclipse/paho.mqtt.android
I can not figure this case out the source code
For example:
mqttAndroidClient1 = new MqttAndroidClient(getApplicationContext(), "tcp://iot.eclipse.org:1883", clientId);
mqttAndroidClient2 = new MqttAndroidClient(getApplicationContext(), "tcp://iot.blablabla.org:1883", clientId);
....
mqttAndroidClient1.connect(...)
mqttAndroidClient2.connect(...)
Ok. It's work. I tested through my locale device and this service https://iot.eclipse.org/getting-started#sandboxes.
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Handler mHandler = new Handler();
MqttAndroidClient mqttAndroidClient1;
MqttAndroidClient mqttAndroidClient2;
String clientId = "ExampleAndroidClient";
final String serverUri = "tcp://iot.eclipse.org:1883";
final String serverUri2 = "tcp://192.168.10.11:1883" ;
#Override
protected void onStart() {
super.onStart();
clientId = clientId + System.currentTimeMillis();
mqttAndroidClient2 = new MqttAndroidClient(getApplicationContext(), serverUri2, clientId+"2");
mqttAndroidClient2.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
if (reconnect) {
Log.i(TAG,"Reconnected to : " + serverURI);
// Because Clean Session is true, we need to re-subscribe
subscribeToTopic2();
} else {
Log.i(TAG,"Connected to: " + serverURI);
}
}
#Override
public void connectionLost(Throwable cause) {
Log.w(TAG,"The Connection was lost.");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG,"Incoming message: " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
mqttAndroidClient1 = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
mqttAndroidClient1.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
if (reconnect) {
Log.i(TAG,"Reconnected to : " + serverURI);
// Because Clean Session is true, we need to re-subscribe
subscribeToTopic1();
} else {
Log.i(TAG,"Connected to: " + serverURI);
}
}
#Override
public void connectionLost(Throwable cause) {
Log.w(TAG,"The Connection was lost.");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG,"Incoming message: " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
try {
//addToHistory("Connecting to " + serverUri);
mqttAndroidClient1.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient1.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic1();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(TAG,"Failed to connect to: " + mqttAndroidClient1.getServerURI());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
try {
//addToHistory("Connecting to " + serverUri);
mqttAndroidClient2.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient2.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic2();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(TAG,"Failed to connect to: " + mqttAndroidClient2.getServerURI());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
public void subscribeToTopic1(){
String subscriptionTopic = "/uwblogs";
try {
mqttAndroidClient1.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG,"Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.i(TAG,"Failed to subscribe");
}
});
mqttAndroidClient1.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// message Arrived!
final String str = new String(message.getPayload());
mHandler.post(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView_server1)).setText(str);
}
});
Log.i(TAG,"Message: " + topic + " : " + new String(message.getPayload()));
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void subscribeToTopic2(){
String subscriptionTopic = "/devices/wb-adc/controls/Vin";
try {
mqttAndroidClient2.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG,"Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.i(TAG,"Failed to subscribe");
}
});
mqttAndroidClient2.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// message Arrived!
final String str = new String(message.getPayload());
mHandler.postAtFrontOfQueue(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView_server2)).setText(str);
}
});
Log.i(TAG,"Message server2: " + topic + " : " + new String(message.getPayload()));
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
}

Android Emitter.Listener not working

I'm making an app with socket IO, it connects correctly to the server, but it doesn't listen to events.
Here's part of my code:
private Socket mSocket;
{
try {
mSocket = IO.socket(ip+":8000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
mSocket.on("send file", onSendFile);
}
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
mSocket.emit("fileok", "OKIDOKI");
}
};
try to show toast on UI thread instead of different thread using getActivity().runOnUiThread
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
mSocket.emit("fileok", "OKIDOKI");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
});
}
};

Android MQTT async subscribe

I just start use MQTT Paho library in my app.
How to make an asynchronous subscription to the topic? (subscription in new thread)
And then in real time to receive the data and display.
It's my code in MainActivity, in main thread:
public void mqttConnect () {
final TextView textView = (TextView) findViewById(R.id.sub_Text_View);
String clientId = MqttClient.generateClientId();
final MqttAndroidClient client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
}
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d("NANADEV", message.toString());
textView.setText(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
final String topic = "testwork/value";
int qos =0;
try {
IMqttToken subToken = client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
Thanks!
In your oncreate
private String uniqueID;
String ip="brokerip";
String port="brokerport usaly 1883"
String broker = "tcp://" + ip + ":" + port;
uniqueID = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
IMqttAsyncClient client= new MqttAsyncClient(broker, uniqueID, new MemoryPersistence());
mqttClient.subscribe("YOURTOPIC/", 0);
mqttClient.subscribe("YOUROTHERTOPIC", 0);
and then in your method:
public void messageArrived(String topic, MqttMessage msg) throws Exception {
Log.i("mqttarrival", "Message arrived from topic " + topic);
if (topic.equals("YOURTOPIC")) {
System.out.println(msg.toString());
}
else {
}
}

Categories

Resources