簡體   English   中英

如何使用Microsoft Java-Client接收SignalR廣播消息?

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

我需要將消息從ASP.NET服務器推送到Android設備,以便在記錄狀態發生變化時發出通知。 所以我想使用來自GitHub的新的Microsoft SignalR Java-Client,使用Eclipse與Android ADT Bundle和Java。

我是Java和SignalR的新手。 我有使用HTML工作的SignalR Hub和JavaScript客戶端,它可以發送和接收消息。 但是我無法進入下一步並讓Java-Client在Eclipse / Java / Android中運行。 我不知道如何注冊接收廣播消息。 當我使用HTML / JavaScript頁面發送消息時,我沒有在Android應用程序中,在模擬器中,在Eclipse中收到消息。 我能夠

我有以下ASP.NET SignalR Hub.cs文件設置:

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

在JavaScript中,我還可以使用從ASP.NET Hub.cs自動生成的Hubs.js文件來通過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!'); });

});

但是,在Eclipse / Java / Android中,我不確定需要使用哪些代碼來接收廣播消息。 我能夠啟動連接並在以下代碼示例的末尾接收connectionID但我被困在那里。 我是否需要以某種方式使用.on()或.subscribe()? 當我運行此代碼時,我看到記錄了連接ID,但我無法從html / JavaScript頁面觸發廣播消息。 沒有收到任何東西,我不會在任何地方收到錯誤。 有誰知道我在這里可能會缺少什么?

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

那么,我是否再次使用proxy.on()來設置接收廣播通知或其他內容? 我傳遞給方法的字符串是什么? 在我的情況下,“broadcastMessage”或者也許是“sendAll”? 任何幫助將不勝感激。

我沒有從問題中顯示的SignalR Hub調用JoinGroup()方法。 您需要加入Hub才能接收廣播是有道理的。 所以在我的后台服務onStart() ,我調用了invoke("JoinGroup", "Group1") 然后我調用on()方法來設置收到的消息的處理程序。 Group1是一個可配置的組名,集線器使用該名稱來拆分廣播,以便不同的組可以使用同一個Hub。 請參閱下面的完整代碼和注釋解決方案塊。 希望這能節省一些時間!

以下是幫助我完成Android后台服務代碼的原因:

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

以下是完整的Android后台服務代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM