websocket的主要是爲了解決在web上應用長鏈接進行靈活的通信應用而產生,但websocket自己只是一個基礎協議,對於消息上還不算靈活,畢竟websocket只提供文本和二進制流這種基礎數據格式.在實際應用則更偏向於對象消息的處理,而在這基礎上更但願集成一系列的消息路由機制來解決消息處理上的問題.爲了解決以上問題beetle針對websocket進行了一些高層次的封裝,讓服務端處理消息變得更簡單靈活.如下經過不一樣的示例介紹Beetle websocket開發包的簡易性. javascript
這個示列是每一個開發語言入門程序,這也經過這樣一個示例來介紹如何使用beetle websocket這個組件.實現一個helloword這樣一個websocket服務是一件很是簡單的事情,具體代碼以下 html
public class HelloServer:BaseServer { [Command("hello")] public void OnList(Beetle.Express.IChannel channel, string id, string command, JToken token) { string result = "hello " +token.ToString(); Send(channel,id,command,result); } }
是否是很是簡單,這樣就是一個簡單的websocket通信服務,那啓動這個服務只須要很簡單的一句話便可 java
mChatServer = new WebChatServer(); mChatServer.Open(9123);
這樣就能夠在9123這個端口開啓服務.接下來web怎麼調用呢?beetle一樣針對websocket的js封裝,因此在js調用這個服務很是簡單. git
<script type="text/javascript"> var wsUri = "ws://127.0.0.1:9125/"; function init() { websocket = new WSClient(); websocket.onConnect = function (evt) { }; websocket.onClose = function (evt) { }; websocket.onReceive = function (evt) { }; websocket.onError = function (evt) { }; websocket.connect(wsUri); $('#cmdconnect').click(function () { websocket.send("hello", $('#txtName').val(), function (result, error) { $('#txtResult').html(result); }); }); } window.addEventListener("load", init, false); </script>
通過封裝後是否是和傳統的處理要簡單不少呢,如下是其運行效果. github
一個基於websocket的hello world示例經過beetle很是簡單就完成,不過實際中應用場並不會這麼簡單,下面經過beetle websocket包進行一個簡單的數據查詢應用場景. web
接下來要作的就是經過beetle websocket通信包進行一個簡單的數據分頁查詢應用. websocket
public class DataServer:BaseServer { [Command("search")] public void Search(Beetle.Express.IChannel channel, string id, string command, JToken token) { int size = 10; int pageindex = token["pageindex"].ToObject<int>(); SearchResult result = new SearchResult(); result.Pages = mCustomers.Count / size; if (mCustomers.Count % size > 0) result.Pages++; for (int i = pageindex * size; i < mCustomers.Count; i++) { result.Items.Add(mCustomers[i]); if (result.Items.Count >= size) break; } Send(channel, id, command, result); } }
代碼是否是很是簡單呢,那js的代碼又如何呢? app
function search() { websocket.send("search", { pageindex: pageIndex }, function (data, error) { $('#lstCustomer').empty(); if (!pages) { pages = data.Pages; createPagination(data.Pages); } for (p = 0; p < data.Items.length; p++) { item = data.Items[p]; createItem(item); } }); } function createPagination(pages) { for (p = 0; p < pages; p++) { $('<li><a href="javascript:pageIndex=' + p + ';search()">' + (p + 1) + '</a></li>').appendTo($('#pagination')); } } function createItem(item) { var html = '<tr>' + '<td>' + item.CustomerID + '</td>' + '<td>' + item.CompanyName + '</td>' + '<td>' + item.Address + '</td>' + '<td>' + item.City + '</td>' + '<td>' + item.Country + '</td>' + '<td>' + item.Phone + '</td>' + '</tr>'; $(html).appendTo($('#lstCustomer')); }
一樣簡單方便的代碼就能完成一個基於websocket的數據分頁查詢 socket
經過以上示例你能夠了解到經過beetle websocket的開發包,能夠很是高效在web開發websocket通信應用,若是你對這個通信包事情興趣能夠到 https://github.com/IKende/websocket.samples 獲取更多的示例(包括在線聊天室) spa