SignalR을 사용하여 컨트롤러에서 클라이언트 그룹으로 메시지를 보내려고합니다. 내 컨트롤러 중 하나에서 이벤트가 발생하면 내 클라이언트 화면에 경고처럼 표시되도록 신호기 허브를 사용하여 메시지를 푸시해야합니다. 나는 많은 질문을 여기에서 물어 보았다. 나는 그들 중 많은 것을 읽고 시도했다. 내가 SignalR을 처음 접한 이래로 그들 중 일부는 이미 사물을 배치하는 데 도움이되었다. 모든 것이 제자리에있는 것 같습니다. 클라이언트는 허브에 연결하고 그룹에 참여할 수 있으며 컨트롤러는 허브에서 메소드를 호출 할 수 있습니다. 그러나 클라이언트는 메시지를받지 못하고 이유를 알 수 없습니다. 나는 컨트롤러에 의해 호출 된 허브의 메소드가 클라이언트를 "보지"않는다고 의심하지만 무엇이 잘못되었는지를 이해할 수 없다.클라이언트가 SignalR 메시지를 수신하지 못했습니다.
허브의 코드 : 여기 public static class UserHandler
{
public static HashSet<string> ConnectedIds = new HashSet<string>();
}
[HubName("myHub")]
public class MyHub : Hub
{
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
public void Notify(string groupName, string message)
{
Clients.Group(groupName).displayNotification(message);
}
public static void Static_Notify(string groupName, string message)
{
var toto = UserHandler.ConnectedIds.Count();
hubContext.Clients.Group(groupName).displayNotification(message);
hubContext.Clients.All.displayNotification(message);//for testing purpose
}
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public override Task OnConnected()
{
UserHandler.ConnectedIds.Add(Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool StopCalled)
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected(StopCalled);
}
}
내 컨트롤러에서 호출입니다 : 여기
public static class UserHandler
{
public static HashSet<string> ConnectedIds = new HashSet<string>();
}
[HubName("myHub")]
public class MyHub : Hub
{
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
public void Notify(string groupName, string message)
{
Clients.Group(groupName).displayNotification(message);
}
public static void Static_Notify(string groupName, string message)
{
var toto = UserHandler.ConnectedIds.Count();
hubContext.Clients.Group(groupName).displayNotification(message);
hubContext.Clients.All.displayNotification(message);//for testing purpose
}
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public override Task OnConnected()
{
UserHandler.ConnectedIds.Add(Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool StopCalled)
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected(StopCalled);
}
}
//(For simplification and readability I define here variables actually obtained by treating some data)
//I already checked that problem did not come from missing data here
string groupName = "theGroupName";
string message = "My beautifull message.";
//prepare signalR call
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
//Following commented lines are different attempts made based on exemples and answers I found here and on others sites.
//The uncommented one is the one in use at the moment and is also based on an answer (from SO i think)
//context.Clients.Group(_userEmail).displayNotification(message);
//context.Clients.Group(_userEmail).Notify(_userEmail,message);
MyHub.Static_Notify(_userEmail, message);
그리고는 클라이언트 측 코드입니다 :
$(document).ready(function() {
var userGroup = 'theGroupName';
$.connection.hub.url = 'http://localhost/SignalRHost/signalr';
var theHub = $.connection.myHub;
console.log($.connection)
console.log($.connection.myHub)
theHub.client.displayNotification = function (message) {
console.log('display message');
alert(message);
};
$.connection.hub.start()
.done(function() {
theHub.server.joinGroup(userGroup);
console.log("myHub hub started : " + $.connection.hub.id)
console.log(theHub)
})
.fail(function() {
console.log('myHub hub failed to connect')
});
});
나를 이해하는 데 도움이됩니다 무엇 논리 나는 이해하지 못했거나 내가 놓친 오류가있다.
는 편집 :
이 알리슨의 코멘트에 대답하려면 :
- 을 : Startup.cs은 나도 얘기를 깜빡 했네요
public void Configuration(IAppBuilder app) { app.Map("/signalr", map => { map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { }; map.RunSignalR(); }); }
중요한 물건을 보여 깜빡 컨트롤러, 허브 및 클라이언트는 3 가지 프로젝트입니다 (글로벌 응용 프로그램 때문에 아키텍처에 나는) 모든 내 로컬 호스트 IIS에 있지만 다른 포트에있는 을 허브 로직을 분리했다
- 나는 "OnConnected"와 "onDiconnected"이벤트에 중단 점을 설정 한 클라이언트가 연결 정상적으로 연결이 끊어
MVC 프로젝트가 로컬 호스트에서 실행되고 있습니까? 로컬 IIS에서 프로젝트를 게시 했습니까, 아니면 Visual Studio에서 IIS Express로 디버깅하고 있습니까? 'Startup.cs' 파일에서 어떻게 SignalR을 설정했는지 공유 할 수 있습니까? – Alisson
중요한 정보를 지적 해 주신 @Alisson에게 언급하는 것을 잊어 버렸습니다. 나는 당신의 질문에 답했다. – Grey
컨트롤러와 허브가 서로 다른 프로젝트에있는 경우 동작하지 않습니다. SignalR 서버로 작동하는 두 개의 프로젝트, 컨트롤러의 프로젝트 및 허브 프로젝트 (두 프로젝트에서 동일한 Hub 클래스를 공유하더라도)가 있습니다. 컨트롤러에서 MyHub.Static_Notify (_userEmail, message);를 호출하면 Hub는 컨트롤러 프로젝트에 연결된 클라이언트를 호출하지만 클라이언트는 실제로 SignalRHost 프로젝트에 연결됩니다. 허브와 컨트롤러에 대해 하나의 고유 한 프로젝트를 사용하거나 컨트롤러가 SignalRHost 프로젝트에서 허브를 호출하도록해야합니다. – Alisson