use*_*883 15 javascript c# signalr
我是使用SignalR(今天开始)的新手,非常简单地向所有连接的客户发送消息,但现在我想发送给一个组.我找不到关于如何在客户端加入的简单文档.如果有人可以提供帮助,我怎么能简单地加入javascript方面的小组.谢谢你的帮助.
public class EventHub : Hub
{
public void SendNewMedia(MediaInfoViewModel model,Guid eventId)
{
Clients.Group(eventId.ToString()).setupmedia(model);
}
}
//Controller that is sending client new data
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
var result = eventHub.Clients.Group(eventId.ToString()).setupmedia(eventViewer);
//Finally the javascript. Not sure how to setup just for a group
$(function () {
var event = $.connection.eventHub;
event.client.setupmedia = function (newMedia) {
$('#photolist').prepend('<li><img src="' + newMedia.MediaUrl + '" class="img-polaroid span2"/></li>');
};
$.connection.hub.start(function() {
event.server.create(eventID);//I know this is wrong but not sure how to connect
}).done(function () {
alert('conntected. Ready to retrieve data!');
});
});
Run Code Online (Sandbox Code Playgroud)
Nik*_*off 31
你不能.如果你可以从javascript加入一个组,那么任何人都可以使用你的代码加入任何破坏安全性的组.如果您确实需要这样做 - 在服务器端创建一个方法,该方法将组名作为参数并将客户端添加到组中.
public void JoinGroup(string groupName)
{
this.Groups.Add(this.Context.ConnectionId, groupName);
}
Run Code Online (Sandbox Code Playgroud)
然后,像这样从JS调用它
eventHub.server.joinGroup("my-awsm-group");
Run Code Online (Sandbox Code Playgroud)
jab*_*a_y 12
--------------------------在 JavaScript (ReactJs) 中-------------------- -------------
const connection = new signalR.HubConnectionBuilder()
.withUrl("connectionUrl")
.build();
connection.start().then(res => {
connection.invoke("JoinGroup", "groupName") //JoinGroup is C# method name
.catch(err => {
console.log(err);
});
}).catch(err => {
console.log(err);
});;
Run Code Online (Sandbox Code Playgroud)
----------------在C#(.Net Core)中-----------------
public class NotificationHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18008 次 |
| 最近记录: |