从外部客户端访问时如何调用signalR disconnected事件

时间:2015-12-14 06:21:03

标签: c#-4.0 asp.net-web-api signalr signalr-hub signalr.client

我的解决方案中有两个项目。

1)mvc项目

2)实现signalR和WebAPI的webapi。 (" http://localhost:8895/signalr/hubs/&#34)

在MVC项目的index.cshtml中我有代码

var baseUrl = "http://localhost:8895/api/webApi/";
var userName = "guest" + getRandom();
$.connection.hub.url = "http://localhost:8895/signalr/hubs/";

var chat = $.connection.chatHub;

 $.connection.hub.start().done(function () {       
    Init();       
});

 //init
 function Init() {
    var req = {
        method: 'POST',
        url: baseUrl + 'Init?username=' + userName + '&connectionId=' +  $.connection.hub.id,
    }
    $http(req)
        .success(function () {

        })
        .error(function (e) {

        });
}

  // Create a function that the hub can call to send welcome message to current connection only.
chat.client.hello = function (clientName) {
   alert(ClientName + " said hello");
};

和第二个项目

  public class webApiController : ApiWithHubController<chatHub>
    { 
      [HttpPost]
       public void chatIntialization(string username, string connectionId)
       {
        chatHub.Hello(username, connectionId);
       } 
    }

和ChatHub.cs

    public class chatHub : Hub
    {
     public static void Hello(string clientName, string connectionId)
     {
        var context = GlobalHost.ConnectionManager.GetHubContext<chatHub>();
        IClientProxy proxy = context.Clients.Client(connectionId);
        proxy.Invoke("Hello", clientName);
     }
   }

运行正常,但现在我要做的是,如果有任何用户断开连接,我需要提醒连接的用户。我无法这样做。

我尝试了什么。

在chathub.cs

    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<chatHub>();
        IClientProxy proxy = context.Clients.All;
       // proxy.Invoke("t", "man down");
        return base.OnDisconnected(stopCalled);
        //return Clients.All.t("man down");
    }

和index.html

  chat.client.disconnect(function (msg) {
     alert(msg);
 })

编辑:

或者如果我取消注释我的行

   // proxy.Invoke("t", "man down");

我按如下方式更改了

     chat.client.t(function (msg) {
     alert(msg);
 })

但是我无法解除断开事件。

0 个答案:

没有答案
相关问题