Connection with Android and Socket failed - android

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"

Related

Socket IO connection fails on 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

RecyclerView: No adapter attached; skipping layout with android socket io

i am trying to make an android realtime chat using node js server and socket.io this is the chatbox activity :
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("messagedetection",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
this is node js server code :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('CHAT' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('CHAT',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})
details about the error :
the server is running correctly it's printing 'server listening on port 3000' in the console . also when i join the chat the socket 'join' and 'disconnect' are emmitted since i get this in my console log:
one user connected xVs1-xYtvNA5sd-dAAAA
one user disconnected xVs1-xYtvNA5sd-dAAAA
only the connect and disconnect socket events are emitted but the send and recevie messages aren't being emitted .
You just need to give the recyclerView an adapter at the same time you give it the layoutManager... It is skipping the layout here when getting the adaper
[UPDATE]
For the socket not emmiting the message on your server you are not listening for the "message" or on the android side you are not listening for the "chat" I would modify your server side code to match your android application as such
Final code:
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("message",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('message' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('message',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})

Chatapp using nodejs and socketio

i am trying to build my chat app. The server side and client side code is attached. when i install it it successfully get installed without giving any error. but it could not communicate to the server i also want that server can handle multiple clients. One thing that is surprising when i install it in my phone it successfully get installed and communicate to server but on any other device or emulator it could not communicate?. how can make this app that multiple clients connects on server and chat?
server side script
const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get('/', (req, res) => {
res.send('Chat Server is running on port 5000')
});
app.set('port',(process.env.PORT||3000))
io.on('connection', (socket) => {
console.log('user connected. id: '+socket.id)
socket.on('join', function(userNickname) {
console.log(userNickname +" : has joined the chat " );
socket.broadcast.emit('userjoinedthechat ',userNickname +" has joined the chat ");
});
socket.on('messagedetection', (senderNickname,messageContent) => {
//log the message in console
console.log(senderNickname+" :" +messageContent)
//create a message object
let message = {"message":messageContent, "senderNickname":senderNickname}
// send the message to the client side
io.emit('message', message );
});
socket.on('disconnect', function() {
console.log( ' user has left ')
socket.broadcast.emit("userdisconnect"," user has left ")
});
});
server.listen(app.get('port'),function(){
console.log('Node app is running on port ',app.get('port'));
});
**Client side**
try {
socket = IO.socket("http://ipaddress:8080").connect();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("messagedetection", Nickname, messagetxt.getText().toString());
messagetxt.setText(" ");
}
}
});
socket.on("join", new Emitter.Listener() {
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
String data = (String) args[0];
socket.emit("join"+Nickname);
}
});
}
});
socket.on("disconnect", new Emitter.Listener() {
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
String data = (String) args[0];
socket.emit("disconnect",Nickname);
// Toast.makeText(ChatBoxActivity.this,data,Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
Message m;
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
m = new Message(nickname,message);
MessageList.add(m);
chatBoxAdapter = new ChatBoxAdapter(MessageList,ChatBoxActivity.this);
chatBoxAdapter.notifyDataSetChanged();
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
enter code here
I tried with node and html. it's working
Client Side
console.log('Server connection started');
var socket = io();
var date = new Date();
var Nickname = "Karthik"+ date.getTime();
socket.on('join', (data) => {
console.log('join', data);
socket.emit("join", Nickname);
})
socket.on('disconnect', (data) => {
console.log('disconnect', data);
socket.emit("disconnect", Nickname);
})
socket.on('message', (data) => {
console.log('message', data);
// socket.emit("message", Nickname);
})
socket.emit("messagedetection", Nickname, 'Hi Test.');
console.log('Server connected', socket);
please check the emit and on function.
Server side
const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static('node_modules'))
app.use(express.static('public'))
app.get('/', (req, res) => {
res.send('Chat Server is running on port 5000')
});
app.set('port', (process.env.PORT || 3000))
io.on('connection', (socket) => {
console.log('user connected. id: ' + socket.id)
socket.on('join', function (userNickname) {
console.log(userNickname + " : has joined the chat ");
socket.broadcast.emit('userjoinedthechat ', userNickname + " has joined the chat ");
});
socket.on('messagedetection', (senderNickname, messageContent) => {
console.log(senderNickname + " :" + messageContent)
//create a message object
let message = { "message": messageContent, "senderNickname": senderNickname }
// send the message to the client side
io.emit('message', message);
});
socket.on('disconnect', function () {
console.log(' user has left ')
socket.broadcast.emit("userdisconnect", " user has left ")
});
});
server.listen(app.get('port'), function () {
console.log('Node app is running on port ', app.get('port'));
});

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