I'm trying to exchange messages between NodeJS server and Android. The Android can connect and send messages to server, but the messages sended by server don't are received on Android.
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
var text = 'BRUNO';
var text2 = 'BRUNO2';
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var clients = [];
io.sockets.on('connection', function (socket) {
socket.emit('news', text);
socket.emit('news', text2);
socket.send('BRUNO');
socket.on('my other event', function (data) {
console.log(data);
console.log(Math.floor((Math.random()*10000)+1));
});
socket.on('name', function (data) {
socket.set('name',data);
console.log('BRUNOOOO');
if (clients.length ==0 )
clients.push(socket);
else {
socket2 = clients.pop()
socket2.join('room');
socket.join('room');
io.sockets.in('room').emit('news','NOVA SALA');
}
socket.get('name', function (err, data) {
socket.emit('news',data);
});
});
});
ANDROID
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtTest;
txtTest = (TextView) findViewById(R.id.txtTeste);
try {
ToServer tos = new ToServer(txtTest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ToServer implements IOCallback {
private SocketIO socket;
private TextView txtTest;
public ToServer(TextView a) throws Exception {
socket = new SocketIO();
this.txtTest = a;
socket.connect("http://nodebruno.jit.su", this);
socket.emit("my other event", "SERVER RECEBEU ANDROID");
}
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
txtTest.setText(json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
txtTest.setText(data);
Log.d("Event",event );
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
@Override
public void onConnect() {
System.out.println("Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
txtTest.setText(event);
Log.d("Event",event );
}
}
On Android i'm using this https://github.com/Gottox/socket.io-java-client
I tried your code and it is working in my case. under override function on i am able to get event and message sent from server.
Try to use this: https://github.com/koush/AndroidAsync And here is demo for implement: https://github.com/Thanhktm/socketio_android