简体   繁体   中英

How to receive SignalR broadcast message using Microsoft Java-Client?

I need to push message from an ASP.NET server to Android devices for a notification whenever the status of a record is changed. So I would like to use the new Microsoft SignalR Java-Client from GitHub using Eclipse with Android ADT Bundle and Java.

I am new to Java and SignalR. I have the SignalR Hub and JavaScript client working in HTML and it can send and receive messages. But I am not able to go to the next step and get the Java-Client to work in Eclipse/Java/Android. I am not sure how to register to receive the broadcast message. When I send a message using the HTML/JavaScript page, I do not receive the message in the Android application, in the emulator, in Eclipse. I am able to

I have the following ASP.NET SignalR Hub.cs file set up:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    using System.Threading.Tasks;

    public class PtThroughputHub : Hub
    {
        public void SendAll(string message)
        {
            Clients.All.broadcastMessage(message);
        }
        public void SendGroup(string groupName, string message)
        {
            Clients.Group(groupName).broadcastMessage(message);
        }
        public Task JoinGroup(string groupName)
        {
            return Groups.Add(Context.ConnectionId, groupName);
        }
        public Task LeaveGroup(string groupName)
        {
            return Groups.Remove(Context.ConnectionId, groupName);
        }
    }

In JavaScript, I am also able to use the Hubs.js file that is auto-generated from the ASP.NET Hub.cs to send and receive messages through the Hub.

<script src="Scripts/jquery-2.1.0.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>    

$(function () {
    $.connection.hub.logging = true;

    // Declare a proxy to reference the hub.
    var ptThroughput = $.connection.ptThroughputHub;
    // Create a function that the hub can call to broadcast messages.
    ptThroughput.client.broadcastMessage = function (message) {
        alert(message);
    };

    // Start the connection.
    $.connection.hub.start()
        .done(function () {
                    alert('Successfully connected as ' + $.connection.hub.id);
                    ptThroughput.server.joinGroup("Group1");
                    $('#btnSend').click(function () {
                        // Call the Send method on the hub.
                        ptThroughput.server.sendGroup('Group1', 'My Message Test Here!');                        
                    })
                })
                .fail(function () { $("#connection").text('Can not connect to SignalR hub!'); });

});

However, in Eclipse/Java/Android I am not sure what code I need to use to receive a broadcast message. I am able to start the connection and receive a connectionID at the end of the following code example but I am stuck there. Do I need to use .on() or .subscribe() somehow? When I run this code I see a connection ID logged but I am not able to trigger the broadcast message from the html/JavaScript page. Nothing is received and I don't get an error anywhere. Does anyone know what I might be missing here?

import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler;

//Setup connection
String server = "http://Servername/Applications/ThroughputMobile/";
HubConnection connection = new HubConnection(server);
HubProxy proxy = connection.createHubProxy("ptThroughputHub");


//--HERE IS WHERE I AM NOT SURE HOW TO SET IT UP TO RECEIVE A NOTIFICATION---
//Setup to receive broadcast message
proxy.on("broadcastMessage",new SubscriptionHandler() {         
    @Override
    public void run() { 
        Log.i("Test Message", "broadcastMessage received..."); 
    }
});
//---------------------------------------------------------------------------

//Start connection
SignalRFuture<Void> awaitConnection = connection.start();
try {
    awaitConnection.get();
} catch (InterruptedException e) {

//Log Connection ID
Log.i("Test Message", "Connection ID = " + connection.getConnectionId());

So again, do I use proxy.on() to set up to receive broadcast notifications or something else? And what string do I pass to the method? "broadcastMessage" or perhaps "sendAll" in my case? Any help would be greatly appreciated.

I was not invoking the JoinGroup() method from the SignalR Hub shown in the Question. It makes sense that you need to join the Hub to be able to receive a broadcast. So in my Background Service onStart() , I call invoke("JoinGroup", "Group1") . Then I call the on() method to set up the handler of the message that gets received. Group1 is a configurable group name that the hub uses to split out broadcasts so different groups can use the same Hub. See the full code and commented solution block below. Hope this save someone some time!

Here is what helped me followed by the full Android Background Service code:

//Invoke JoinGroup to start receiving broadcast messages            
proxy.invoke("JoinGroup", "Group1");

//Then call on() to handle the messages when they are received.        
proxy.on( "broadcastMessage", new SubscriptionHandler1<String>() 
{
  @Override
  public void run(String msg) {
      Log.d("result := ", msg);                 
  }
}, String.class);

Here is the full Android Background Service code:

import java.util.concurrent.ExecutionException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import microsoft.aspnet.signalr.client.*;
import microsoft.aspnet.signalr.client.hubs.*;

public class NotifyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();       
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {      
            super.onStart(intent, startId);       
            Toast.makeText(this, "Service Start", Toast.LENGTH_LONG).show();       

        String server = "http://Servername/Applications/ThroughputMobile/";
            HubConnection connection = new HubConnection(server);
            HubProxy proxy = connection.createHubProxy("ptThroughputHub");

            SignalRFuture<Void> awaitConnection = connection.start();
            try {
                awaitConnection.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }          

        //--HERE IS MY SOLUTION-----------------------------------------------------------
        //Invoke JoinGroup to start receiving broadcast messages            
        proxy.invoke("JoinGroup", "Group1");

        //Then call on() to handle the messages when they are received.        
            proxy.on( "broadcastMessage", new SubscriptionHandler1<String>() {
                @Override
                public void run(String msg) {
                    Log.d("result := ", msg);                   
                }
            }, String.class);

        //--------------------------------------------------------------------------------
    }
    @Override
    public void onDestroy() {
       super.onDestroy();       
    }   
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM