參考文章:http://www.cnblogs.com/nywd/p/3691813.html
上一節,已經實現了,當前域內的通信,這一節中,介紹一下跨域的即時通信,既然要做,我們肯定要把這個推送及聊天服務器做為一個單獨的服務器,以方便擴展使用,這樣就要使用跨域技術,既然基於ajax,那么跨域肯定是基於jsonp,下面我們介紹一下跨域的基本配置:
1、服務器的配置,我們打開項目中的Global.asax,在Application_Start中做如下配置:
protected void Application_Start() { var config = new HubConfiguration(); config.EnableCrossDomain = true; RouteTable.Routes.MapHubs(config); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); }
config.EnableCrossDomain = true;
這句代碼,就指定了當前的所有集線器都可以跨域進行使用。
2、web端配置,我們新建一個項目,然后添加一個html頁面,msg.html,添加header部分:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="/Scripts/json2.js" type="text/javascript"></script> <script src="/Scripts/jquery.signalR-1.0.1.min.js" type="text/javascript"></script> <script src="http://localhost:2154/signalr/hubs" type="text/javascript"></script>
http://localhost:2154/signalr/hubs 就是我們推送服務器的地址了,如果真正上線了,肯定使用推送服務器的域名地址,如:push.xxx.com,然后我們來寫js方法,html部分基本一致:
<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>
1、首先要指定hub根地址:$.connection.hub.url = "http://localhost:2154/signalr";
2、啟動連接時,添加跨域參數: $.connection.hub.start({ xdomain: true});
很簡單,現在配置已經完成了,我們來啟動瀏覽器測試一下:
可以看到,2個web服務器之間已經實現了互通,而且我們指定使用ie7,說明兼容性是很好的,xp都淘汰了ie6咱也就不測了: )。
接下來我們要做什么,找個ui設計師,把我們站點的聊天窗口美化一下,做個iframe,在右下角,點擊,既出現我們的聊天界面,然后和其他客戶端的用戶還有我們的客服人員進行聊天,是不是很贊,
要開飯了,明天我們繼續介紹客戶端連接SignalR,以實現商家客戶端和用戶直接通信。