10

We have a SignalR hub. The following jQuery code connects and properly processes SignalR client "call" events successfully on cordova.

        var connectionURL = "https://SOMEURL.azurewebsites.net/message";
        connection = $.connection(connectionURL);

        connection.start().done(function () {
            console.log("Connected to hub again");
        });

        connection.disconnected(function () {
            setTimeout(function () {
                connection.start().done(function () {
                    console.log("Disconnected and Connected to hub again");
                });
            }, 5000);
        });

        connection.stateChanged(function (change) {
            if (change.newState == $.signalR.connectionState.reconnecting) {
            }
            else if (change.newState == $.signalR.connectionState.connected) {
            }
            else if (change.newState == $.signalR.connectionState.disconnected) {
            }// else if 
        });

        connection.received(function (data) {
            connectId = connection.id + "";
            console.log("onDeviceReady run");

            // call the function to parse the data
            if (data.PayloadType == "Dispatch") {
                dataDispatch(data);
            }
            if (data.PayloadType == "ConnectionAcknowledge") {
                sendConnectionAcknowledge(data);
            }
        });

However when I try to emulate this code in java android using the SignalR Java Client, I get a lot of log output (tonnes), and no connection ever finishes. it gets as far as the debug at line awaitConnection.get(); and never prints the second line of debug, instead it prints endless (thousands) of lines of semi gibberish (it's not piping, it's like it's some sort of "SSL handshake" but it's not doing anything but logging the same thing repeatedly, very odd) anyway it never runs the 2nd line of "my" debug

package com.some.thing;

import android.util.Log;

import java.util.concurrent.ExecutionException;

import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;

public class SignalRClient {

    public static void startConnection() {

        Platform.loadPlatformComponent(new AndroidPlatformComponent());
        String host = "https://SOMEURL.azurewebsites.net/message";
        HubConnection connection = new HubConnection(host);
        HubProxy hub = connection.createHubProxy( "IDoNoHaveThisNorKnowIt" );

        SignalRFuture<Void> awaitConnection = connection.start();
        try {
            Log.v("CONANSignalR :=", "CONNECTING");
            awaitConnection.get();
            Log.v("CONANSignalR :=", "CONNECTED");
        } catch (InterruptedException e) {
            // Handle ...
        } catch (ExecutionException e) {
            // Handle ...
        }

        hub.on("IDoNotKnowThisEither", new SubscriptionHandler1<String>(){
            @Override
            public void run( String status ){
                Log.v("CONANDispatch :=", status);
            }
        }, String.class);
    }
}

Can anyone help me translate the working, jQuery SignalR client code into usable java client code? I don't have any information on the hub so I cannot know the proxy or the function names, I'd like to see everything (like the jQuery).

EDIT

To test things, I have altered my original jquery code it use to say

console.log("onDeviceReady run");

now it says

console.log("SignalR Raw Data:" + JSON.stringify(data));

when I do this this is what the jquery returns

SignalR Raw Data:{"ConnectionId":"9c4b4ba5-cb6e-4dcb-8df9-069cbf749873","OrderId":null,"SenderId":null,"PayloadType":"ConnectionAck","Message":"Welcome, you are connected to the Hub!","Payload":null,"Initiator":"HUB","Version":null}

however none of this appears inside the java equivalent

connection.received(new MessageReceivedHandler() {
    @Override
    public void onMessageReceived(JsonElement json) {
        System.out.println("RAW received message: " + json.toString());

        // ADD HANDLING OF RECEIVED IN HERE
    }
});

i.e. the text "RAW received message:" doesn't appear at all

user26676
  • 280
  • 3
  • 21
  • I would like it known, that @drax s response was very helpful however he was NOT able to answer the question and admitted so, and it was based on a link I already had access to, (at this time no connection to the hub has occurred following his advice) but it appears the bounty is going to be auto sent to him anyway – user26676 Apr 17 '15 at 14:22

1 Answers1

3

Since you don't know hub name, you have to use handle events on connection object directly (like you do in js client).

Here is sample code which could get you started (note, this is not tested, written just from top of my head):

public static void startConnection() {

    Platform.loadPlatformComponent(new AndroidPlatformComponent());
    String host = "https://SOMEURL.azurewebsites.net/message";
    HubConnection connection = new HubConnection(host);

    // subscribe to received - equal to `connection.received(function (data)` from javascript 
    connection.received(new MessageReceivedHandler() {

        @Override
        public void onMessageReceived(JsonElement json) {
            System.out.println("RAW received message: " + json.toString());

            // ADD HANDLING OF RECEIVED IN HERE
        }
    });

    // equal to `connection.disconnected(function ()` from javascript
    connection.closed(new Runnable() {

        @Override
        public void run() {
            // ADD CODE TO HANDLE DISCONNECTED EVENT
        }
    });

    // equal to `connection.stateChanged(function (change)`
    connection.stateChanged(new StateChangedCallback() {

        @Override
        public void stateChanged(ConnectionState oldState, ConnectionState newState) {
            // ADD CODE TO HANDLE STATE CHANGES
        }
    });

    // start the connection
    connection.start()
        .done(new Action<Void>() {

            @Override
            public void run(Void obj) throws Exception {
                System.out.println("Connected");
            }
        });
}

Also, I recommend you to check sample chat client for java which can be found here: https://github.com/SignalR/java-samples/blob/master/signalr-sample-chat/src/microsoft/aspnet/signalr/samples/chat/Program.java

Most of code I posted is based on that one.

Marian Polacek
  • 2,906
  • 4
  • 30
  • 37
  • thanks @drax I have made the changes, there is my results in the edit, this is definitely an improvement re `connecting`, but `received` is not firing – user26676 Apr 10 '15 at 11:32
  • one thing, that comes to my mind is, that `connection` object in your java sample goes out of scope (and might be garbage collected) in the end of `startConnection` function. You should probably assign it to some program-wide (static or such) variable. – Marian Polacek Apr 11 '15 at 08:08
  • thanks @drax , yeah, I looked at global scope / GC issues during my enormous fiddling, it was fruitless, I would be willing to remunerate you for your time if you were to take a look at this? my email is conanman _at_ live _dotco_dotuk it has taken 6 days of my time, yet I am sure it is a minor issue, somethig I have overlooked. I can send you the src of my project if u like (android studio) – user26676 Apr 11 '15 at 10:04
  • sadly, I'm not really experienced in adroid development, so I probably wouldn't be of much help – Marian Polacek Apr 12 '15 at 09:55
  • have your found the solution for this @user26676 – M.Yogeshwaran Nov 07 '16 at 13:52