I have developed an iPhone application with socket.io, it is working fine with HTTP and HTTPS.
I have developed Android application with socket.io. I was using HTTP it was working fine. Now I am trying to use HTTPS. I made some changes, but it is not at all connecting with server. Always I am getting websocket error.
I downloaded the library from https://github.com/socketio/ for iPhone and Android
Below is my sample code
try {
HostnameVerifier verifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
// Not doing any validation for testing
Log.i(TAG, "Verifying host name ::: " + hostname);
return true;
}
};
IO.setDefaultSSLContext(SSLContext.getDefault());
IO.setDefaultHostnameVerifier(verifier);
IO.Options opts = new IO.Options();
opts.reconnection = false;
opts.secure = true;
opts.transports = new String [] {WebSocket.NAME};
socket = IO.socket("https://website.com:6001", opts);
Log.i(TAG, "Initialized socket io");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "We are connected to server");
}
});
socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "We are disconnected from server");
socket.off();
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "Connection Error");
for (Object obj : args) {
Log.e(TAG, "Errors :: " + obj);
}
}
});
socket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "Connection Timeout Error");
}
});
socket.on("res", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "got response from server");
}
});
socket.connect();
} catch (Exception e) {
Log.e(TAG, "Error :: " + e);
}
Any idea ?
Related
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.
I'm trying to create a simple chat using Socket IO, Android and Node.
When I run the app and try to connect to the server, it always fails with a timeout error and I can't figure out why.
Here's the Node code:
app = require('express')()
http = require('http').createServer(app)
io = require('socket.io')(http)
app.get('/', (req,res) => {
res.send('Chat server is running on port 5000')
})
/**
* Defines a listener to an event called connection and this event will be fired from the client side
*/
io.on('connection', (socket) => {
console.log('user connected')
})
http.listen(5000, () => {
console.log('Node app is running on port 5000')
})
Here's the Android code (Editted according to Marcos Casagrande Answer:
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.engineio.client.transports.WebSocket;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
if(intent.hasExtra(NICKNAME)){
mNickname = intent.getStringExtra(NICKNAME);
Log.d(TAG, "chatapp onCreate: " + mNickname);
}
try {
IO.Options opts = new IO.Options();
opts.transports = new String[]{WebSocket.NAME};
mSocket = IO.socket("http://10.0.0.21:5000", opts);
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "chatapp call: connected to server");
}
});
mSocket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, " chatapp call: disconnected from the server");
}
});
mSocket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "chatapp call: connection error");
}
});
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "chatapp call: connection timeout");
}
});
mSocket.connect();
} catch (Exception e) {
Log.d(TAG, "onCreate: something unexpected happened");
e.printStackTrace();
}
I try to run the app on virtual device through Android Studio I keep getting Connection timeout error. Can someone tell me, what am I doing wrong?
The connection won't happen instantly, it's asyncrhonous, attach the correct handlers and check for connection or errors in there.
mSocket = IO.socket("http://localhost:5000");
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
// ....
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "connected...");
// This doesn't run in the UI thread, so use:
// .runOnUiThread if you want to do something in the UI
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Error connecting...");
}
};
I recommend using WebSocket transport in android, to avoid polling errors, you can check my answer here:
How to set transports for SocketIO in Android?
You have to use 2 AVD's instead of physical devices to connect with this IP. If now try with http://10.0.2.2:5000
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();
}
});
}
};
I am trying to learn basic MQTT integration in Android. I am using a mosquitto broker to publish and subscribe messages. I am running the code on a real device and getting this exception :
Unable to connect to server (32103) - java.net.ConnectException:
failed to connect to /192.168.0.103 (port 1883) after
30000ms: isConnected failed: ECONNREFUSED
Here's my code:
public class HomeActivity extends AppCompatActivity{
private MqttAndroidClient client;
private final MemoryPersistence persistence = new MemoryPersistence();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.103:1883", "androidSampleClient", persistence);
mqttAndroidClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
System.out.println("Connection was lost!");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery Complete!");
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
System.out.println("Connection Success!");
try {
System.out.println("Subscribing to /test");
mqttAndroidClient.subscribe("/test", 0);
System.out.println("Subscribed to /test");
System.out.println("Publishing message..");
mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
} catch (MqttException ex) {
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
System.out.println("Connection Failure!");
System.out.println("throwable: " + exception.toString());
}
});
} catch (MqttException ex) {
System.out.println(ex.toString());
}
}
}
I've tried using different ports but the error is same. Can anyone help what am i doing wrong?
As you are getting started, you need to see see how different implementations work. Take a look at my implementation. I use a separated class for MQTT specific stuff.
MqttUtil.java
public class MqttUtil {
private static final String MQTT_TOPIC = "test/topic";
private static final String MQTT_URL = "tcp://localhost:1883";
private static boolean published;
private static MqttAndroidClient client;
private static final String TAG = MqttUtil.class.getName();
public static MqttAndroidClient getClient(Context context){
if(client == null){
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(context, MQTT_URL, clientId);
}
if(!client.isConnected())
connect();
return client;
}
private static void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setKeepAliveInterval(30);
try{
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "onFailure. Exception when connecting: " + exception);
}
});
}catch (Exception e) {
Log.e(TAG, "Error while connecting to Mqtt broker : " + e);
e.printStackTrace();
}
}
public static void publishMessage(final String payload){
published = false;
try {
byte[] encodedpayload = payload.getBytes();
MqttMessage message = new MqttMessage(encodedpayload);
client.publish(MQTT_TOPIC, message);
published = true;
Log.i(TAG, "message successfully published : " + payload);
} catch (Exception e) {
Log.e(TAG, "Error when publishing message : " + e);
e.printStackTrace();
}
}
public static void close(){
if(client != null) {
client.unregisterResources();
client.close();
}
}
}
And you can simply use it in your HomeActivity. Check it below:
public class HomeActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get Mqtt client singleton instance
MqttUtil.getClient(this);
// Publish a sample message
MqttUtil.publishMessage("Hello Android MQTT");
}
}
For testing purposes, use your Mosquitto sub client and see if you get the message.
Hope that helps!
try using port 8883
String clientId = MqttClient.generateClientId();
final MqttAndroidClient client =
new MqttAndroidClient(this.getApplicationContext(), "ssl://iot.eclipse.org:8883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
InputStream input =
this.getApplicationContext().getAssets().open("iot.eclipse.org.bks");
options.setSocketFactory(client.getSSLSocketFactory(input, "eclipse-password"));
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException | IOException e) {
e.printStackTrace();
}
I'm developing a simple WebSocket in Android using AndroidAsync library:
http://www.koushikdutta.com/AndroidAsync
My Client code:
private void conectar() {
//String uri = "ws://192.167.101.142:1234";
String uri = "http://192.167.101.166:1234";
AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance();
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(uri, "https", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), null, new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "SSL", new AsyncHttpClient.WebSocketConnectCallback() {
asyncHttpClient.websocket(uri, null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.e(TAG, "webSocket is null");
Log.e(TAG, "Metodo onCompleted");
if (ex != null) {
Log.e(TAG, ex.getMessage(), ex);
return;
}
//Log.e(TAG, "webSocket.isOpen(): " + webSocket.isOpen());
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
Log.e(TAG, "I got a string: " + s);
//showToast("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
#Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
Log.e(TAG, "I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
}
My Server code:
private void conectar() {
AsyncHttpServer server = new AsyncHttpServer();
server.listen(PORTA);
server.get("/", new HttpServerRequestCallback() {
#Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.websocket("/", new AsyncHttpServer.WebSocketRequestCallback() {
#Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
Log.e(TAG, "Metodo: onConnected");
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
webSocket.setClosedCallback(new CompletedCallback() {
#Override
public void onCompleted(Exception ex) {
Log.e(TAG, "Metodo onCompleted from webSocket object");
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new WebSocket.StringCallback() {
#Override
public void onStringAvailable(String s) {
Log.e(TAG, "Metodo onStringAvailable from webSocket object");
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
Anyone knows tell me why Can't I connect my server?
I have tested the server code in another app websocket tester from google play.
The app server it's Ok.
However I cannot connect from my client app?