Git Product home page Git Product logo

Comments (3)

sathish-valleru-19 avatar sathish-valleru-19 commented on July 30, 2024

hello, anyone has same issue.

from nv-websocket-client.

ivanov199311 avatar ivanov199311 commented on July 30, 2024

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

from nv-websocket-client.

sathish-valleru-19 avatar sathish-valleru-19 commented on July 30, 2024

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

from nv-websocket-client.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.