简体   繁体   English

Socket.io 类异常

[英]Socket.io Class exception

Trying to create a sample app which listens to local server on Node.js server.尝试创建一个示例应用程序,它侦听 Node.js 服务器上的本地服务器。 Getting errors.获取错误。 I am Using https://socket.io/blog/native-socket-io-and-android/ for my tutorial.我正在使用https://socket.io/blog/native-socket-io-and-android/作为我的教程。

App.js Server App.js 服务器

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主要活动.java

package com.example.zest.sampleproject;包 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.我们正在使用 Rabbitmq 将消息传递到本地服务器。 The msgs are coming to local server correctly but when I am parsing them in Android app it crashes.消息正确地到达本地服务器,但是当我在 Android 应用程序中解析它们时它崩溃了。 I don't have pom.xml btw.我没有 pom.xml 顺便说一句。 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.但在日志中它是:{[com.github.nkzawa.socketio.client.Socket$7]} 对于每个味精。

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:-您的应用程序正在崩溃,因为您正在将 socketio 客户端对象类型转换为 JSON,如下行中的错误所述(com.github.nkzawa.socketio.client.Socket$7 无法转换为 org.json.JSONObject):-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM