Saya mengalami masalah dengan Websocket ws is closed with code: 1006 reason:

Lingkungan

Amazon EC2 Instance  : t2.micro Ubuntu 18.04
Node : v12.16.3
Websocket : https://github.com/websockets/ws : 7.3.0
MongoDb : shell version v4.2.6
MongoDriver : NodeJs 3.5.7
Okhhtp3 : implementation 'com.squareup.okhttp3:okhttp:4.6.0'

Saya mendapatkan data dari Websockets -> MongoDb dan mencoba mengisi ke tampilan pendaur ulang. Data datang dengan baik jika saya melakukan log.d tetapi ketika saya mengisi ke tampilan pendaur ulang - itu baik-baik saja pada peluncuran aplikasi, dan sekali lagi ketika datang ke aktivitas tetapi setelah itu saya mulai mendapatkan kesalahan 1006.

NodeJs (Server)

// Websocket variables
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8000 });
console.log('Websocket active on port 8000...');

// Connect To Mongo
MongoClient.connect(url, { useUnifiedTopology: true, authSource: 'admin' }, function (err, client) {
    if (err) {
        throw err;
    }

    const db = client.db(dbName);

    // New Connection
    wss.on('connection', function connection(ws) {

        // Message Received
        ws.on('message', function incoming(message) {

            // Json Parse String To Access Child Elements
            var iJson = JSON.parse(message);
            const c = db.collection('chats');
            c.find({ "owner": iJson.owner_id }).toArray(function (err, docs) {
                ws.send(JSON.stringify(docs));
            });
        });

        // Connection Closed
        ws.on('close', function close(code, reason) {
            console.log('ws is closed with code: ' + code + ' reason: ' + reason);
        });
    });
});

Android (Klien)

private WebSocket webSocket;

// Initiate The Socket Connection
private void initiateSocketConnection() {

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(WebSocketClient.SERVER_PATH).build();
    webSocket = client.newWebSocket(request, new SocketListener());

}

// Private WebSocketListener Class
private class SocketListener extends WebSocketListener {

    public SocketListener() {
        super();
    }

    @Override
    public void onClosed(@NotNull WebSocket webSocket,
        int code,
        @NotNull String reason) {
        super.onClosed(webSocket,
            code,
            reason);

        Log.d("TAG",
            "onClosed: " + code + "-" + reason);

    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket,
        @NotNull Throwable t,
        okhttp3.@org.jetbrains.annotations.Nullable Response response) {
        super.onFailure(webSocket,
            t,
            response);
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket,
        @NotNull String text) {
        super.onMessage(webSocket,
            text);

        String chat = "{\"chat\":" + text + "}";

        Log.d("TAG",
            "onMessage: " + chat);

        lIndividualChatList.clear();

        try {
            JSONObject jsonObject = new JSONObject(chat.trim());

            // Check If User Array Has Anything
            JSONArray returnArray = jsonObject.getJSONArray("chat");

            for (int l = 0; l < returnArray.length(); l++) {
                if (returnArray.length() > 0) {

                    // Get The Json Object
                    JSONObject returnJSONObject = returnArray.getJSONObject(l);

                    // Get Details
                    String owner = returnJSONObject.optString("owner");
                    lIndividualChatList.add(new IndividualListModel(owner));
                }
            }

            // Use The Adapter To Populate The Recycler View
            aIndividualChatList = new IndividualListAdapter(lIndividualChatList);
            rvList.setAdapter(aIndividualChatList);

            aIndividualChatList.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket,
        okhttp3.@NotNull Response response) {
        super.onOpen(webSocket,
            response);
    }
}
1
DragonFire 20 Mei 2020, 13:31

1 menjawab

Jawaban Terbaik

Bagian yang aneh adalah ia bekerja sekali atau dua kali sebelum gagal yang menyebabkan kebingungan. Jika selalu gagal dan menyukai logcat itu pasti menyenangkan. Cara terbaik adalah mencatat semua kemungkinan kesalahan/kegagalan di server dan klien dan melihat pesannya.

Pertama Masukkan Log Di Dalam Jika Gagal

@Override
public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, okhttp3.@org.jetbrains.annotations.Nullable Response response) {
    super.onFailure(webSocket, t, response);

    Log.d("TAG", "websocket failure: " + t + response);
}

Itu memberikan pesan berikut :

: `websocket failure: android.view.ViewRootImpl$CalledFromWrongThreadException: 
Only the original thread that created a view hierarchy can touch its views.null`

Kemudian Bungkus populasi tampilan pendaur ulang dalam ini

getActivity().runOnUiThread(new Runnable() {
public void run() {

  // Poplulate the recycler view here....

}
0
DragonFire 21 Mei 2020, 01:07