首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用接收SignalR广播消息?

如何使用接收SignalR广播消息?
EN

Stack Overflow用户
提问于 2014-09-26 20:17:44
回答 1查看 12.5K关注 0票数 7

我需要将消息从ASP.NET服务器推送到安卓设备,以便在更改记录状态时发出通知。因此,我想使用新的客户端--来自SignalR的GitHub,使用和Java。

我对Java和SignalR很陌生。我让SignalR集线器和JavaScript客户端在HTML中工作,它可以发送和接收消息。但我无法进入下一步,让Java客户机在Eclipse/Java/Android中工作。我不知道如何登记以接收广播信息。当我使用HTML/JavaScript页面发送消息时,我不会在Android应用程序、模拟器和Eclipse中接收消息。我能

我设置了以下ASP.NET SignalR Hub.cs文件:

代码语言:javascript
代码运行次数:0
运行
复制
    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文件通过集线器发送和接收消息。

代码语言:javascript
代码运行次数:0
运行
复制
<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页面触发广播消息。什么都没有收到,我在任何地方都没有错误。有人知道我在这里可能错过了什么吗?

代码语言:javascript
代码运行次数:0
运行
复制
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”在我的例子中?任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2014-10-02 14:32:11

我没有从问题中显示的JoinGroup()集线器调用SignalR方法。您需要加入集线器才能接收到广播,这是有意义的。因此,在我的后台服务onStart()中,我打电话给invoke("JoinGroup", "Group1")。然后调用on()方法来设置接收到的消息的处理程序。Group1是集线器用来分割广播的可配置组名,以便不同的组可以使用相同的集线器。请参阅下面的完整代码和注释解决方案块。希望这能节省一些时间!

下面是帮助我编写完整Android后台服务代码的内容:

代码语言:javascript
代码运行次数:0
运行
复制
//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后台服务代码:

代码语言:javascript
代码运行次数:0
运行
复制
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;
    }
}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26067685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档