Comments (3)
hello, anyone has same issue.
from nv-websocket-client.
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.
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)
- getting below when i try subscribe my payload from Server sometimes
- why getListenerManager() getStateManager() and others are private ? HOT 1
- Denied app upload to PlayStore HOT 3
- How can I have a listener for each sendText Method? HOT 1
- Very misleading error message if jdk.crypto.ec module is missing
- NV WebSocket Client & Quarkus & GraalVM Native Image Problems HOT 1
- Race between WebSocketAdapter.onConnected() and .onTextMessage().
- websocket client send performance
- While multiple send, download is blocked
- -
- Crashes on API < 24 with new AGP that is needed for API 33 HOT 8
- Websocket disconnects automatically after 30 seconds HOT 3
- Handshake failure with basic Authorization
- Websocket makes two connections HOT 1
- how to get session id to send messages
- Throws Exception even if the url is valid
- Does the library use some Tracking link?
- Upgrade SHA-1 to SHA-256 in HandshakeReader
- Ability to replace threads
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nv-websocket-client.