Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sathish-valleru-19 opened this issue Mar 16, 2021 · 3 comments

Comments

@sathish-valleru-19
Copy link

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
Copy link
Author

hello, anyone has same issue.

@ivanov199311
Copy link

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
Copy link
Author

sathish-valleru-19 commented Dec 8, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants