使用SignalR从wcf通知JS



我想使用SignalR来识别WCF service上的Jquery客户端,并在没有请求的情况下向他发送消息。(即在客户向服务发送第一个请求后,服务可以了解他并向他发送消息)。

我不知道这是否是最好的方法,但这是我所能找到的。(只有VS 2012才支持WebSocket除外)。

我在服务上的Global文件中添加了以下功能:

protected void Application_Start(object sender, EventArgs e)
{
   RouteTable.Routes.MapHubs();
}

我创建了Chat.cs:

public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients
        Clients.All.addMessage(message);
    }
}

JS项目中,我添加了SignalR:的JS文件

<script src="../JavaScript/jquery.signalR-1.1.2.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>

使用它的函数:

function Chat() {
    $(function () {
        // Proxy created on the fly          
        var chat = $.connection.chat;
        // Declare a function on the chat hub so the server can invoke it          
        chat.client.addMessage = function (message) {
            alert(message);
        };
        // Start the connection
        $.connection.hub.start().done(function () {
            // Call the chat method on the server
            chat.server.send('aa');
        });
    });
}

这对我来说是一件新鲜事,很抱歉,如果这个问题很愚蠢,但JS的SignalR应该如何了解服务,我应该在哪里定义他?(这需要跨域)

(变量$.connection.chat未定义)

我肯定错过了一些东西,尤其是他如何通过SignalR链接服务和JS的主要内容?

我缺少的是使用SignalR和跨域

在全局文件中,我更改了代码:

protected void Application_Start(object sender, EventArgs e)
{
  RouteTable.Routes.MapHubs(new HubConfiguration() { EnableCrossDomain = true });
}

这里需要注意的是,由于我使用跨域,我在Application_BeginRequest函数中有代码,在完成SignalR请求时应该取消它,否则它将不起作用。所以我这样取消了:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Here is testing whether this request SignalR, if not I do the following code
            if (HttpContext.Current.Request.Path.IndexOf("signalr") == -1)
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                {
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, x-requested-with");
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                    HttpContext.Current.Response.End();
                }
            }
        }

在客户端上:

我添加了SignalRJquery的脚本,并删除了这个脚本:

<script src="/signalr/hubs" type="text/javascript"></script>

因为存在跨域调用,所以不需要

连接在以下功能中:

var connection;
var contosoChatHubProxy;
function RegisterToServiceMessege() {
    connection = $.hubConnection();
    connection.url = 'http://localhost:xxx/signalr';
    contosoChatHubProxy = connection.createHubProxy('ChatHub');
    //This part happens when function broadcastMessage is activated(from the server)
    contosoChatHubProxy.on('broadcastMessage', function (userName, message) {
        alert('You have a messege:n' + userName + ' ' + message);
    });
    connection.start()
    .done(function () {
        console.log('Now connected, connection ID=' + connection.id);
    })
    .fail(function () { console.log('Could not connect'); });
}

服务器上的聊天:

 [HubName("ChatHub")]
    public class Chat : Hub
    {
        [HubMethodName("Send")]
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }
    }

其中一个客户对函数Send的调用如下:

function SendMessege() {
    contosoChatHubProxy.invoke('Send', 'aaa', 'bbb').done(function () {
        console.log('Invocation of NewContosoChatMessage succeeded');
    }).fail(function (error) {
        console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);
    });
}

所有客户端都会收到发送的消息

(您可以通过同时运行多个浏览器来检查这一点。)

由于SignalR的2.0版本,您不能再使用以下代码启用Cors:

protected void Application_Start(对象发送方,EventArgs e){RouteTable.Routes.MapHubs(new HubConfiguration(){EnableCrossDomain=true})}

相反,您必须在Startup类初始化方法中添加这两行:

public void Configuration(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll);
    app.MapSignalR();           
}

而且,对每个人来说可能并不明显的是,如果你不想使用SignalR的自托管库托管SignalR,那么记得将你的项目更改为WebApplication。在我的案例中,我试图将Signalr附加到WCFProject。运行时甚至不会使用这种启动的配置方法,因此会导致不断的错误,禁止访问信号资源