2014-01-24 16 views
1

我想发送一条消息给一个SignalR客户端,但它不应该广播给所有人,我经历了许多关于clientId和组的文章,但没有直接的例子或给出的观点。我的客户端代码如下:客户端特定的消息由信号R

proxy: null,

//Getting the connection object 
connection = .hubConnection('url') 

//Creating proxy 
this.proxy = connection.createHubProxy('SignalRServerHub'); 
this.proxy.on('displayStatus', function (a) { 
    SignalRMessageTableService.getDataFromServer() 
}); 

//Starting connection 
connection.start() 
//we are able to capture connection.id here 
//under .done function but not sure how to use 

请让我知道一步一步的解决方案或引用的文章,所以我可以很容易地理解它。

+0

谁将消息发送给给定客户端?另一个客户端或服务器? – scheien

+0

回到客户端的服务器消息 – freedom

回答

4

对特定的客户进行响应的ConnectionId,你可以做这样的事情:

 var connectionId = Context.ConnectionId; 
     Clients.Client(connectionId).someMethod(resultValue); 

或者只响应来电:

Clients.Caller.someMethod(resultValue); 

这些电话是从公共方法内进行你的中心班,并做同样的事情。

编辑:

它看起来像connection.start()应扩大一点。如果服务器要返回数据或回调到调用者的事件,则不需要处理connectionId。这将由服务器完成,并通过上述方法处理。

尝试改变connection.start()行是这样的:

connection.start().done(function() { 
    $('#someButton').click(function() { 
     var param1 = $('#someField').val(); 
     var param2 = $('#someField2').val(); 
     this.proxy.invoke('myHubMethod', param1, param2, paramN); 
    }); 
}); 

执行neccessary更改此应用到YOUT实施。此代码基于您将在文档中找到的代码。由于看起来您不使用生成的代理,因此我们使用代理上的invoke方法来确定我们要发送哪个方法以及哪些参数。这也将一个事件连接到一个按钮id=someButton,点击时将触发集线器上的myHubMethod

另一种方法是像(与生成的代理):

this.proxy.server.myHubMethod(param1, param2, paramN); 

如果你想将消息发送到特定的用户,您应该采取对ASP.NET SignalR Hubs API Guide - JavaScript Client

+0

但是,我怎么能得到connectionId,它是任何GUID genarated在服务器或用户定义的ID从客户端发送。请建议。 – freedom

+0

尝试使用Context.ConnectionId(与Client.Caller相同)。 connectionId(guid)由服务器为每个客户端生成。 – scheien

+0

@scheien美好的一天。什么是Clients.Caller.someMethod(resultValue)中的某些方法;?这是客户端的一个功能吗? – Amelina

0

一看,你可以使用版本2.0中的新方法

Clients.User(userId).send(message); 

默认情况下,使用的用户标识是IPrincipal.Identity.Name。如果您想用自己的映射覆盖用户ID机制,请参阅此回复 - https://stackoverflow.com/a/21355406/2489038

相关问题