Reputation: 135
Trying to create a sample app which listens to local server on Node.js server. Getting errors. I am Using https://socket.io/blog/native-socket-io-and-android/ for my tutorial.
App.js Server
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var amqp = require('amqplib/callback_api');
var port = 8000;
var que = "Test"
var ex = "livestream"
var messages = [];
app.use(express.static(path.join(__dirname, "public")));
io.on('connection', (socket) => {
console.log('new connection made');
socket.emit('Test', (data)=>{
console.log("sending message :%s", messages);
socket.emit('Test',{msg:messages[0]
});
});
});
amqp.connect('amqp://52.37.151.97', function (err, conn) {
console.log("connection made");
conn.createChannel(function (err, ch) {
ch.on("close",function(err){
console.error("[ aqmp]c channel error",err.messages);
});
ch.on("close",function(){
console.log("Channel closed");
});
ch.assertExchange(ex, 'topic', { durable: false });
console.log()
ch.assertQueue('Test', { durable: false }, function (err, q) {
ch.prefetch(1);
console.log(' [*] Waiting for logs. To exit press CTRL+C');
ch.bindQueue(q.queue, ex, "alert");
console.log(q.queue);
ch.consume(q.queue, function(msg) {
ch.ack(msg);
console.log(" [x] %s: '%s'", msg.fields.routingKey, msg.content.toString());
messages.push(msg.content.toString());
console.log("messages[0] :",messages[0]);
// JSON.parse(msg)
},
{
noAck: false
});
});
});
});
server.listen(port, () => {
console.log("Listening on port " + port);
});
Main Activity.java
package com.example.zest.sampleproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.emitter.Emitter;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.122.1:8000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private EditText editText;
private Button button;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on("Test", onNewMessage);
mSocket.connect();
mSocket.open();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptSend();
}
});
}
private void attemptSend() {
String message = editText.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
textView.setText("");
mSocket.emit("new message", message);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
//Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
Log.e("IsConnected:", String.valueOf(mSocket.connected()));
mSocket.open();
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject object = (JSONObject) args[0];
Log.e("Length:", String.valueOf(args.length));
Log.e("Msg", object.toString());
}
});
}
};
}
My dependencies:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.nkzawa:socket.io-client:0.5.0'
implementation ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
}
Errors:
08-22 18:40:05.600 3588-3651/com.example.zest.sampleproject E/IsConnected:: true
08-22 18:40:05.676 3588-3588/com.example.zest.sampleproject D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-22 18:40:05.676 3588-3588/com.example.zest.sampleproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zest.sampleproject, PID: 3588
java.lang.ClassCastException: com.github.nkzawa.socketio.client.Socket$7 cannot be cast to org.json.JSONObject
at com.example.zest.sampleproject.MainActivity$3$1.run(MainActivity.java:106)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I want to just listen to the msgs incoming. We are using Rabbitmq for passing the msgs to local server. The msgs are coming to local server correctly but when I am parsing them in Android app it crashes. I don't have pom.xml btw. Don't know what it is
EDIT: Ok I tried printing it with logs by converting it to String. but in logs it was : {[com.github.nkzawa.socketio.client.Socket$7]} for every msg.
Upvotes: 1
Views: 1054
Reputation: 456
Your app is crashing since your are type casting a socketio client object to JSON as the error says (com.github.nkzawa.socketio.client.Socket$7 cannot be cast to org.json.JSONObject) in below line:-
JSONObject object = (JSONObject) args[0];
Here is how you should do it:-
Log.e("onNewMessage:- ", args[0].toString()); //Log to check incoming message
JSONObject object = new JSONObject(args[0].toString());
Upvotes: 1