vs2010 使用SignalR 提升B2C商城用户体验(二)javascript
上一节,已经实现了,当前域内的通讯,这一节中,介绍一下跨域的即时通讯,既然要作,咱们确定要把这个推送及聊天服务器作为一个单独的服务器,以方便扩展使用,这样就要使用跨域技术,既然基于ajax,那么跨域确定是基于jsonp,下面咱们介绍一下跨域的基本配置:html
一、服务器的配置,咱们打开项目中的Global.asax,在Application_Start中作以下配置:java
1 protected void Application_Start() 2 { 3 var config = new HubConfiguration(); 4 config.EnableCrossDomain = true; 5 RouteTable.Routes.MapHubs(config); 6 AreaRegistration.RegisterAllAreas(); 7 8 WebApiConfig.Register(GlobalConfiguration.Configuration); 9 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 10 RouteConfig.RegisterRoutes(RouteTable.Routes); 11 12 }
config.EnableCrossDomain = true;
这句代码,就指定了当前的全部集线器均可以跨域进行使用。jquery
二、web端配置,咱们新建一个项目,而后添加一个html页面,msg.html,添加header部分:web
1 <script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> 2 <script src="/Scripts/json2.js" type="text/javascript"></script> 3 <script src="/Scripts/jquery.signalR-1.0.1.min.js" type="text/javascript"></script> 4 <script src="http://localhost:2154/signalr/hubs" type="text/javascript"></script>
http://localhost:2154/signalr/hubs 就是咱们推送服务器的地址了,若是真正上线了,确定使用推送服务器的域名地址,如:push.xxx.com,而后咱们来写js方法,html部分基本一致:ajax
<script type="text/javascript"> $(function () { $.connection.hub.url = "http://localhost:2154/signalr"; // Proxy created on the fly var chat = $.connection.pushHub; // Declare a function on the chat hub so the server can invoke it chat.client.addMessage = function (message) { writeEvent('<b>ny</b> 对你们说: ' + message, 'event-message'); }; $("#broadcast").click(function () { // Call the chat method on the server chat.server.send($('#msg').val()) .done(function () { console.log('Sent message success!'); }) .fail(function (e) { console.warn(e); }); }); // Start the connection $.connection.hub.start({ xdomain: true}); //A function to write events to the page function writeEvent(eventLog, logClass) { var now = new Date(); var nowStr = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(); $('#messages').prepend('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>'); } }); </script>
一、首先要指定hub根地址:$.connection.hub.url = "http://localhost:2154/signalr";json
二、启动链接时,添加跨域参数: $.connection.hub.start({ xdomain: true});跨域
很简单,如今配置已经完成了,咱们来启动浏览器测试一下:浏览器
能够看到,2个web服务器之间已经实现了互通,并且咱们指定使用ie7,说明兼容性是很好的,xp都淘汰了ie6咱也就不测了: )。服务器
接下来咱们要作什么,找个ui设计师,把咱们站点的聊天窗口美化一下,作个iframe,在右下角,点击,既出现咱们的聊天界面,而后和其余客户端的用户还有咱们的客服人员进行聊天,是否是很赞,
要开饭了,明天咱们继续介绍客户端链接SignalR,以实现商家客户端和用户直接通讯。