TakahikoKawasaki / nv-websocket-client

High-quality WebSocket client implementation in Java.
Apache License 2.0
2.03k stars 292 forks source link

getting below errors after socket opened and when i try to subscribe my payload from Server sometimes #230

Open sathish-valleru-19 opened 3 years ago

sathish-valleru-19 commented 3 years ago

1st Error: handleCallbackError: java.util.TreeMap cannot be cast to java.lang.Throwable

2nd error: @Override public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception { super.handleCallbackError(websocket, cause); Log.i(TAG, " handleCallbackError: " + cause.getMessage()); }

handleCallbackError: java.lang.RuntimeException: Can't create handler inside thread Thread[WritingThread,5,main] that has not called Looper.prepare()

because of 2nd error sometimes i could not able to subscribe my payload and no updates from server

sathish-valleru-19 commented 3 years ago

hello, anyone has same issue.

ivanov199311 commented 2 years ago

It would greatly increase fix chance if you provide a code snippet to reproduce the issue(and use some markdown). Because now it seems that problem is not in this lib: handleCallbackError: java.lang.RuntimeException: Can't create handler inside thread Thread[WritingThread,5,main] that has not called Looper.prepare() There is no Looper in codebase and so such error message

sathish-valleru-19 commented 2 years ago

Hi, Here is the Socket manager class which i written for Socket connection and data subscription. `public class SocketManager {

private static final String TAG = SocketManager.class.getCanonicalName();
public boolean isConnecting;
boolean isCreated;
private WebSocketFactory socketFactory;
static WebSocket webSocket;
private SocketDataCallback socketDataCallback;
private static SocketManager mInstance = new SocketManager();

public static SocketManager getInstance() {
    if (mInstance == null) {
        mInstance = new SocketManager();
    }

    return mInstance;
}

public SocketManager() {
    isCreated = true;
    socketFactory = new WebSocketFactory();
    socketFactory.setVerifyHostname(false);
}

/**
 * establish webSocket connection.
 */
public void connectWebSocketWithTimeout(String endPoint, String idToken, SocketDataCallback socketDataCallback) {
    this.socketDataCallback = socketDataCallback;

    try {
        webSocket = socketFactory.createSocket(endPoint, 600000);
        webSocket.addHeader("Authorization", idToken);
        webSocket.addListener(webSocketAdapter);
        webSocket.connectAsynchronously();
        webSocket.setPingInterval(120 * 1000);
        isConnecting = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * method to subscribe the full shadow.
 */
public void subscribe(int userId, String serialNumber, String nameSpace, String action) {
    JSONObject jsonObject1 = new JSONObject();
    JSONObject jsonObject2 = new JSONObject();

    try {
        jsonObject1.put("service", "Authorization");
        jsonObject1.put("target", serialNumber);
        jsonObject1.put("namespace", nameSpace);
        jsonObject1.put("version", 1);
        jsonObject1.put("action", action);
        jsonObject2.put("userId", userId);
        jsonObject1.put("payload", jsonObject2);
    } catch (JSONException e) {
        Log.e(TAG, "Subscribe parsing exception: " + e.getMessage());
    }
    Log.i(TAG, "Subscribe Json: " + jsonObject1.toString());
    sendFrames(jsonObject1.toString());
}

/**
 * method to unSubscribe shadow.
 */
public void unSubscribeSocketData(int userId, String serialNumber, String nameSpace, String action) {
    JSONObject tcxDeviceInfoObject = new JSONObject();
    JSONObject payloadObject = new JSONObject();
    try {
        tcxDeviceInfoObject.put("service", "Authorization");
        tcxDeviceInfoObject.put("target", serialNumber);
        tcxDeviceInfoObject.put("namespace", nameSpace);
        tcxDeviceInfoObject.put("version", 1);
        tcxDeviceInfoObject.put("action", action);
        payloadObject.put("userId", userId);
        tcxDeviceInfoObject.put("payload", payloadObject);
    } catch (JSONException e) {

    }

    sendFrames(tcxDeviceInfoObject.toString());
}

/**
 * post socket data.
 */
public void postData(int userId, String serialNumber, String nameSpace, String action, String payloadInput) {
    JSONObject jsonObject1 = new JSONObject();
    JSONObject jsonObject2;

    try {
        jsonObject1.put("service", "StateController");
        jsonObject1.put("target", serialNumber);
        jsonObject1.put("namespace", nameSpace);
        jsonObject1.put("version", 1);
        jsonObject1.put("action", action);
        jsonObject2 = new JSONObject(payloadInput).put("clientToken", userId + "|" + getRandomTokens() + "|" + getRandomTokens());
        jsonObject1.put("payload", jsonObject2);
    } catch (JSONException e) {

    }

    sendFrames(jsonObject1.toString());
    isConnecting = false;
}

private static void sendFrames(String frame) {
    if (webSocket != null && !TextUtils.isEmpty(frame) && webSocket.isOpen()) {
        webSocket.sendText(frame);
        }
}

private static String getRandomTokens() {
    UUID uuid = UUID.randomUUID();
    byte[] uuidArr = asByteArray(uuid);
    String s = Base64.encodeToString(uuidArr, Base64.DEFAULT);
    String trimmed = s.split("=")[0];
    return trimmed;
}

private static byte[] asByteArray(UUID uuid) {

    long msb = uuid.getMostSignificantBits();
    long lsb = uuid.getLeastSignificantBits();
    byte[] buffer = new byte[16];

    for (int i = 0; i < 8; i++) {
        buffer[i] = (byte) (msb >>> 8 * (7 - i));
    }
    for (int i = 8; i < 16; i++) {
        buffer[i] = (byte) (lsb >>> 8 * (7 - i));
    }

    return buffer;
}

/**
 * socket response callbacks.
 */
private final WebSocketAdapter webSocketAdapter = new WebSocketAdapter() {

    @Override
    public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {

    }

    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        super.onTextMessage(websocket, text);
        int maxLogSize = 1000;
        for (int i = 0; i <= text.length() / maxLogSize; i++) {
            int start = i * maxLogSize;
            int end = (i + 1) * maxLogSize;
            end = end > text.length() ? text.length() : end;
            Log.v(TAG, text.substring(start, end));
        }

        socketDataCallback.onReceiveData(text);
    }

    @Override
    public void onDisconnected(WebSocket websocket,
                               WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
                               boolean closedByServer) throws Exception {
        super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);

        if (closedByServer || clientCloseFrame.getCloseCode() == SocketErrorCodes.GOING_AWAY_1001.getId() || clientCloseFrame.getCloseCode() == SocketErrorCodes.NO_MORE_FRAMES_1002.getId()) {
            socketDataCallback.onReconnect();
        }
    }

    @Override
    public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
        super.onConnectError(websocket, exception);

    }

    @Override
    public void onError(WebSocket websocket, WebSocketException cause) throws Exception {
        super.onError(websocket, cause);

    }

    @Override
    public void onMessageError(WebSocket websocket, WebSocketException cause, List<WebSocketFrame> frames) throws Exception {
        super.onMessageError(websocket, cause, frames);
    }

    @Override
    public void onTextMessageError(WebSocket websocket, WebSocketException cause, byte[] data) throws Exception {
        super.onTextMessageError(websocket, cause, data);
    }

    @Override
    public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception {
        super.handleCallbackError(websocket, cause);
    }

    @Override
    public void onPongFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
        super.onPongFrame(websocket, frame);
        //sendPingFrame();
    }

    @Override
    public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception {
        Log.i(TAG, newState.name());
        if (newState.name().equalsIgnoreCase(WebSocketState.CLOSED.name())) {
            socketDataCallback.isReadyToSubscribe(false);
        }
    }

    @Override
    public void onThreadStarted(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception {
        super.onThreadStarted(websocket, threadType, thread);
        if (threadType.name().equalsIgnoreCase(ThreadType.WRITING_THREAD.name())) {
            socketDataCallback.isReadyToSubscribe(true);
        }
    }
};