SignalR negotiate method calling in loop sometimes in 24 hours - android

I have used below code to connect with hub.
Its working proper. but sometime suddenly the negotiate GET method calls thousands of time.
private HubConnection createLocalHubConnection() {
if (Common.isInternetAvailable(CallObserverTestService.this)) {
Log.i(TAG, "Create Connection");
final HubConnection loConnection = new HubConnection(WebService.getHubURL(CallObserverTestService.this));
Log.i(TAG, "Connection State1: " + loConnection.getState());
if (loConnection.getState() == ConnectionState.Disconnected) {
moProxy = loConnection.createHubProxy(CallObserverTestService.this.getString(R.string.hub));
try {
loConnection.stop();
loConnection.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.i(TAG, "Connection URL: " + loConnection.getUrl());
Log.i(TAG, "SignalR ConnectionId: " + loConnection.getConnectionId());
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "SignalR: onError : " + error.getMessage());
error.printStackTrace();
Log.logException(TAG, error);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.logException(TAG, e);
}
}
return loConnection;
}
return null;
}
The error is as below while calling in loop
Negotiation error: There was a problem in the negotiation with the
server
negotiate: https://MyDomain/signalr/negotiate?clientProtocol=1.3&connectionData=%5B%7B%22name%22%3A%22MyHubName%22%7D%5D
Reference link: https://github.com/SignalR/java-client/tree/master/signalr-client-sdk

Related

Cannot connect to node websocket from android okhttp3

I've created a node server on top of expressJs and used socket.io to create a websocket server. Code i've used to create the server is
io.sockets.on('connection', function (socket) {
connections.push(socket);
console.log('Connected: ' + connections.length + 'sockets connected');
io.sockets.emit('connected', JSON.stringify({status: "online"}));
socket.on('disconnect', function (data) {
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: ' + connections.length + ' sockets connected');
io.sockets.emit('disconnected', {status: "offline"});
});
socket.on('request', function (data) {
console.log('new request in server: ' + data.toString());
io.sockets.emit('newRequest', JSON.stringify({request: data}));
})
});
I can connect with the server from any browser including mobile and emulator browser, But i failed to connect using okhttp3 websocket.
I am following https://gist.github.com/AliYusuf95/557af8be5f360c95fdf029795291eddb this gist to create the client. but i failed to connect with the websocket. I'm getting the following error
D/OkHttp: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on Connection{192.***.0.***:3000, proxy=DIRECT# hostAddress=/192.***.0.***:3000:3000 cipherSuite=none protocol=http/1.1}
What's going wrong?
Try the following...see if that works.
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://websockethost:8080");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView)findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
Source

Add topic/subscription after stomp client is connected

I am currently using
https://github.com/NaikSoftware/StompProtocolAndroid
to connect websocket using STOMP. I have a simple implementation as
public class TestActivity extends AppCompatActivity {
private StompClient mStompCLient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
mStompCLient = Stomp.over(WebSocket.class, BASE_URL);
mStompCLient.topic("/topic/online/" + mSharedPreferences.getPrivateKey()).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG, "/topic/online/ onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, "/topic/online/ onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, "/topic/online/ onNext: " + stompMessage.getPayload());
String content = "";
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(stompMessage.getPayload());
content = jsonResponse.getString("uri");
} catch (JSONException e) {
e.printStackTrace();
}
listenToUpdatesFromFinalUri(content);
}
});
mStompCLient.lifecycle().subscribe(lifecycleEvent -> {
Log.i(TAG, "onCreate: " + lifecycleEvent.getMessage());
switch (lifecycleEvent.getType()) {
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed : " + lifecycleEvent.toString() + " :msg: " + lifecycleEvent.getMessage() + " :escep: " + lifecycleEvent.getException() + " :headers: " + lifecycleEvent.getHandshakeResponseHeaders() + " :type: " + lifecycleEvent.getType());
break;
}
});
mStompCLient.connect();
}
private void listenToUpdatesFromFinalUri(String content) {
mStompCLient.topic(content).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG," onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, " onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, " onNext: " + stompMessage.getPayload());
}
});
}
#Override
protected void onStop() {
super.onStop();
disconnectStomp();
}
private void disconnectStomp() {
mStompCLient.disconnect();
}
}
Here I am trying to listen to the new subscription channel sent by the server after connection is established. It works if the subscribe() is called before the connect is called. But the final uri/subscription channel subscribed in listenToUpdatesFromFinalUri() function is not static so I need can't add subscription before the connect. I am currently unable to get response for the final uri/subscription. Any help is appreciated.
The issue has been solved in the new version 1.1.6

Getting status code 404 and service connection error while calling api using Pipe (Aerogear)

I am implementing Keycloak for user and api authentication and successfully authenticate with Keyclaok server but getting error while calling API .
I am using aerogear pipe library and sample project to call server API.
https://github.com/aerogear/aerogear-android-pipe
try{
AuthzModule authzModule = AuthorizationManager.config("keycloak", OAuth2AuthorizationConfiguration.class)
.setBaseURL(new URL("URL:8080/auth"))
.setAuthzEndpoint("/realms/appname/tokens/login")
.setAccessTokenEndpoint("/realms/appname/tokens/access/codes")
.setAccountId("keycloak-token")
.setClientId("app_id")
.setClientSecret("1b9a1376-bc6e-41d2-b3e5-cee754305a1f")
.setRedirectURL("Callback")
.setScopes(Arrays.asList("user"))
.addAdditionalAuthorizationParam((Pair.create("access_type", "confidential")))
.asModule();
authzModule.requestAccess(this, new Callback<String>() {
#Override
public void onSuccess(String o) {
System.out.println("Server Response" + o);
retrieveFiles(authzModule);
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
PipeManager.config("GetFile", RestfulPipeConfiguration.class)
.withUrl(new URL("Server_URL"))
.module(authzModule)
.forClass(String.class);
Pipe<Object> documentsPipe = PipeManager.getPipe("GetFile", this);
documentsPipe.read(new Callback<List<Object>>() {
#Override
public void onSuccess(final List<Object> fileses) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
Please suggest possible way to resolved this issue.
try{
AuthzModule authzModule = AuthorizationManager.config("keycloak", OAuth2AuthorizationConfiguration.class)
.setBaseURL(new URL("URL:8080/auth"))
.setAuthzEndpoint("/realms/appname/tokens/login")
.setAccessTokenEndpoint("/realms/appname/tokens/access/codes")
.setAccountId("keycloak-token")
.setClientId("app_id")
.setClientSecret("1b9a1376-bc6e-41d2-b3e5-cee754305a1f")
.setRedirectURL("Callback")
.setScopes(Arrays.asList("user"))
.addAdditionalAuthorizationParam((Pair.create("access_type", "confidential")))
.asModule();
authzModule.requestAccess(this, new Callback<String>() {
#Override
public void onSuccess(String o) {
System.out.println("Server Response" + o);
retrieveFiles(authzModule);
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
Than call simple http request with auth token in header.when server sending json response.
Headers:Bearer +" auth token",
Content-Type : application/json,
Accept : application/json

Why websocket from AndroidAsync always null

I'm developing a simple WebSocket in Android using AndroidAsync library:
http://www.koushikdutta.com/AndroidAsync
My Client code:
private void conectar() {
//String uri = "ws://192.167.101.142:1234";
String uri = "http://192.167.101.166:1234";
AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance();
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(uri, "https", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), null, new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "SSL", new AsyncHttpClient.WebSocketConnectCallback() {
asyncHttpClient.websocket(uri, null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.e(TAG, "webSocket is null");
Log.e(TAG, "Metodo onCompleted");
if (ex != null) {
Log.e(TAG, ex.getMessage(), ex);
return;
}
//Log.e(TAG, "webSocket.isOpen(): " + webSocket.isOpen());
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
Log.e(TAG, "I got a string: " + s);
//showToast("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
#Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
Log.e(TAG, "I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
}
My Server code:
private void conectar() {
AsyncHttpServer server = new AsyncHttpServer();
server.listen(PORTA);
server.get("/", new HttpServerRequestCallback() {
#Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.websocket("/", new AsyncHttpServer.WebSocketRequestCallback() {
#Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
Log.e(TAG, "Metodo: onConnected");
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
webSocket.setClosedCallback(new CompletedCallback() {
#Override
public void onCompleted(Exception ex) {
Log.e(TAG, "Metodo onCompleted from webSocket object");
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new WebSocket.StringCallback() {
#Override
public void onStringAvailable(String s) {
Log.e(TAG, "Metodo onStringAvailable from webSocket object");
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
Anyone knows tell me why Can't I connect my server?
I have tested the server code in another app websocket tester from google play.
The app server it's Ok.
However I cannot connect from my client app?

Using Autobahn for WebSocket comms, not receiving from Server

I'm implement Autobahn to connnect to a server through WebSockets. When I hit connect, it opens the socket correctly and logs that socket is opened. I then try to send a request to the server which is simply {"request":"getSoftwareVersion"} , when the server receives this, it should send back the software version in a JSON object, the trouble is, that onMessage is never hit. Here is my code:
public class AutoBahnConnectRequest extends Request{
private static WebSocketConnection mAutoBahnConnection;
private String mSocketHostAddress;
private final static String m_TAG = AutoBahnConnectRequest.class.getSimpleName();
public AutoBahnConnectRequest(String SocketHostAddress){
this.mAutoBahnConnection = new WebSocketConnection();
this.mSocketHostAddress = SocketHostAddress;
}
#Override
protected Void doInBackground(Void... params){
try {
mAutoBahnConnection.connect(mSocketHostAddress, new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
});
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}
return null;
}
}
This has been implemented with a html client like so (not with autobahn):
function getSoftwareVersion() {
socket_di.send('{"request":"getSoftwareVersion"}');
}
and the onMessage receives the data. Can someone please tell me if I'm doing something wrong here?
Thank you.
I have figured out my issue regarding this. The WebSocket connection required a protocol and options to be added. So I changed this:
mAutoBahnConnection.connect(mSocketHostAddress, new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
});
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}
to this:
mAutoBahnConnection.connect(mSocketHostAddress,new String[]{"this is my protocol"} ,new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onRawTextMessage(byte[] payload) {
try {
rawText = new String(payload, "UTF-8");
Log.i(m_TAG, "ON RAW TEXT");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onBinaryMessage(byte[] payload) {
Log.i(m_TAG, "ON BINARY MESSAGE");
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
}, options);
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}

Categories

Resources