Socket IO connection fails on Android - android

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

Related

Connection with Android and Socket failed

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"

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 - Socket.io - no logs, no connection

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

how to join socket room or channel in Socket.IO-client in android

I'm new to socket programming and in a project i'm using Socket.IO-client Java to create socket connection between android device and a server . server side developers asked me to connect to the server and then join in a specific room/channel . I'm OK with the first part but how can i join in a room over socket ??
my code is as below :
private void ConnectAndJoin() {
Log.e("starting:","starting!");
final Socket socket;
try {
socket = IO.socket("http://192.168.1.6:5000");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("foo", "hi");
Log.e("status:","connected- sent");
socket.
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("status:","event2");
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("status:","disconnected");
}
});
socket.connect();
} catch (URISyntaxException e) {
Log.e("status:","done with error");
}
Please give me a help!
You can't join a room with socket io from the client side . it should happens in the server side.
socket.emit('join-room' , roomName or RoomId)
to tackle this you need to emit a socket with the room you want to join as data , and in the server you listen to this socket and call socket.join() with the name or the id of the room that has been sent.
socket.on("join-room", new Emitter.Listener() {
#Override
public void call(Object... args) {
room = args[0];
socket.join(room);
}
});
warning : I do not know java so for java devs if you see a syntax mistake you can comment i'll update it
hope it helps!

How to use HTTPS in Android SocketIO?

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 ?

Categories

Resources