I'm trying to use socket.io/engine.io (https://github.com/socketio/socket.io-client-java) to connect to websocket server. I wrote any point as the guthub page described, but I have no connection, even no log that something happens or not.. EVENT_CONNECTED is not fired. I don't know what is the problem- maybe socket.IO is not working with android 5.1UP? The websocket server is tested with JS and is working fine.
There is my very simple code, it will be great if you know socket.io and could take a look:
Ws implementation:
public class MyWsImplInIo {
private Socket socket;
public void start(){
try{
socket = IO.socket("http://192.168.1.8:8080/tmed-webserver/call");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("foo", "hi");
socket.disconnect();
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
});
socket.connect();
} catch(Exception e){
Log.d("WEBSOCKET", "SOME ERROR");
e.printStackTrace();
}
}
}
And a main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyWsImplInIo a = new MyWsImplInIo();
a.start();
}
}
Related
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 want to create a connection between my node.js page and my java application
I'm trying to link this node.js page, this page :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("Load ...");
res.sendFile(__dirname+"/index.html");
});
io.on('connection', function(socket){
console.log('one user connected : ' + socket.id);
});
http.listen(3000 ,function(){
console.log('Start server on port 3000');
});
with this java code:
My socke, this page is just to tell me if someone has joined the socket, the page is hosted on http://192.168.0.12:3000/ :
private Socket socket;
{
try{
socket = IO.socket("http://192.168.0.12:3000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
My listeners, here I'am just testing what type of errors i get:
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Connect", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Errors", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Timeout", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.connect();
I always have the same error Socket.EVENT_CONNECT_ERROR.
My node.js work on network but
My code node.js works for internet browsers but not on android, I think this from configuration but what I do not know.
Thank you
First,check if your android device can even access the node.js server
go the browser in your device and request the same url
it's maybe you cannot access the resource in the first place
The solution:
just add this in manifest:
android:usesCleartextTraffic="true"
using mqtt for push notification in android with following libs :
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
i followed this tutorial , the problem is it works properly when app is open , but when it is swiped from recent apps , it stops working and I can't receive push notifications anymore
any help is appreciated
solutions i tried :
first solution : created a service and simply created a mqttclient in it , but after swiping from recent apps didn't work anymore
public class MqttService extends Service {
public MqttService(Context context) {
super();
}
public MqttService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PahoDemo paho = new Paho(getApplicationContext(), "myTopic");
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent = new Intent("com.example.restart");
sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent("com.example.restart");
sendBroadcast(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PahoDemo :
public class Paho implements MqttCallback {
String topic;
MqttClient client;
Context context;
public Paho(Context context, String topic) {
this.context = context;
this.topic = topic;
try {
client = new MqttClient(StaticValue.getBROKER(), MqttClient.generateClientId(), persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
client.connect(connOpts);
client.setCallback(this);
if (topic != null) {
client.subscribe(topic);
}
} catch (MqttException e) {
System.out.println("error: " + e);
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i("mqtt", "messageArrived ");
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i("mqtt", token + "");
}
}
second solution:
added the below line to manifest :
<service android:name="org.eclipse.paho.android.service.MqttService" />
called this helper class from mainactivty's Oncreate :
public class MqttHelper {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "myBrokerUri";
final String clientId = MqttClient.generateClientId();
final String subscriptionTopic = "myTopic";
public MqttHelper(Context context){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallbackExtended callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(true);
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
subscribeToTopic();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt","Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exceptionst subscribing");
ex.printStackTrace();
}
}
}
that's all i did since tow days ago . if someone has any ideas , please mention .
when messageArrived is called , you shouldn't use something you don't access to . for example if you wanna check app is in foreground , you may use context , this way your logic may doesn't work properly , so make sure you do what you can do in messageArrived and if you aren't sure the objects you use are available do it another way (also be careful about connectinLost )
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 working on an android chat application .I am not able to connect to my server using Socket.Io client in android.
1.ChatActivity.java
public class ChatActivity extends Activity {
EditText edMessage;
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
edMessage = (EditText) findViewById(R.id.edtMessage);
String message = edMessage.getText().toString().trim();
mSocket.connect();
// mSocket.emit("subscribe", "Testing");
mSocket.on("subscribe", subscribe);
}
private Emitter.Listener subscribe = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String room = (String) args[0];
Log.e("Response", room);
}
});
}
};
}
Please help me to solve the issue.I am not able to verify whether the server is connected or not .