簡體   English   中英

Socket.io 類異常

[英]Socket.io Class exception

嘗試創建一個示例應用程序,它偵聽 Node.js 服務器上的本地服務器。 獲取錯誤。 我正在使用https://socket.io/blog/native-socket-io-and-android/作為我的教程。

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

主要活動.java

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

}

我的依賴:

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

錯誤:

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)

我只想收聽傳入的消息。 我們正在使用 Rabbitmq 將消息傳遞到本地服務器。 消息正確地到達本地服務器,但是當我在 Android 應用程序中解析它們時它崩潰了。 我沒有 pom.xml 順便說一句。 不知道是什么

編輯:好的,我嘗試通過將其轉換為字符串來使用日志打印它。 但在日志中它是:{[com.github.nkzawa.socketio.client.Socket$7]} 對於每個味精。

您的應用程序正在崩潰,因為您正在將 socketio 客戶端對象類型轉換為 JSON,如下行中的錯誤所述(com.github.nkzawa.socketio.client.Socket$7 無法轉換為 org.json.JSONObject):-

JSONObject object = (JSONObject) args[0];

這是你應該怎么做:-

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