websocket的主要是為了解決在web上應用長連接進行靈活的通訊應用而產生,但websocket本身只是一個基礎協議,對於消息上還不算靈活,畢竟websocket只提供文本和二進制流這種基礎數據格式.在實際應用則更偏向於對象消息的處理,而在這基礎上更希望集成一系列的消息路由機制來解決消息處理上的問題.為了解決以上問題beetle針對websocket進行了一些高層次的封裝,讓服務端處理消息變得更簡單靈活.以下通過不同的示例介紹Beetle websocket開發包的簡易性.
hello world
這個示列是每個開發語言入門程序,這也通過這樣一個示例來介紹如何使用beetle websocket這個組件.實現一個helloword這樣一個websocket服務是一件非常簡單的事情,具體代碼如下
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通訊服務,那啟動這個服務只需要很簡單的一句話即可
mChatServer = new WebChatServer();
mChatServer.Open(9123);
這樣就可以在9123這個端口開啟服務.接下來web怎么調用呢?beetle同樣針對websocket的js封裝,所以在js調用這個服務非常簡單.
<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>
經過封裝后是不是和傳統的處理要簡單很多呢,以下是其運行效果.

一個基於websocket的hello world示例通過beetle非常簡單就完成,不過實際中應用場並不會這么簡單,下面通過beetle websocket包進行一個簡單的數據查詢應用場景.
數據查詢
接下來要做的就是通過beetle 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的代碼又如何呢?
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的數據分頁查詢

總結
通過以上示例你可以了解到通過beetle websocket的開發包,可以非常高效在web開發websocket通訊應用,如果你對這個通訊包事情興趣可以到 https://github.com/IKende/websocket.samples 獲取更多的示例(包括在線聊天室)
