微軟Asp.net2.0 Ajax
一. Asp.net 2.0 Ajax
執行環境需求:
Framework 2.0
IIS
開發環境:
VS2005 C#.net (or VB.net)
微軟 Ajax 套件 (需另外下載)
1.下載套件:
http://ajax.asp.net/
於首頁 按下 Download ASP.NET AJAX v1.0
會進入下一個頁面
點下 Download ASP.NET Extensions V1.0 即可 下載
安裝完成後 開啟 VS2005
新增專案 選擇(VB 或 C#) Asp.net Ajax-Enabled Web Application
開啟後會發現 多了 1組元件在 工具箱 (Ajax Extensions)
2.介紹AJAX Extensions
ASP.NET AJAX v1.0 使用微軟自定的 Client Script Libery
1.ScriptManager控制項 – 整個 Asp.net Ajax 的核心 ,所有要使用Ajax的功能均必須使用該元件 ,負責建立User端的javascript ,使用Ajax功能時只能有一個ScriptManager控制項。
2.UpdatePanel控制項 – 與ScriptManager搭配使用後 ,可以簡單建立完成Ajax功能。
3.UpdateProgress控制項 – 與UpdatePanel 配合 ,用來顯示 非同步postback的處理狀況 ,或將非同步postback中斷。
4.Timer 控制項 – 就如同windows應用程式所使用的Timer 元件 ,可定時於page中重整 ,但時間設定太短可能會增加Server的負擔。
5.ScriptManagerProxy 控制項 – 在Asp.net Ajax的page裡只能用一個ScriptManager, 於Asp.net MasterPage(類似Html 的框架頁)會有多個Asp.net page,如果同時間有2個以上的網頁要使用Ajax功能需使用到 ScriptManager 則子版面必須使用ScriptManagerProxy
範例(一) AspNetAJAXdemo.aspx
配合 Asp.Net 2.0 的MasterPage 解說 這5大Asp.Net Ajax 控制項 的使用方式
二. Asp.Net Ajax Control Toolkit
Asp.Net Ajax Control Toolkit 為 Asp.Net Ajax 的強化套件 , 已有34項免費延伸元件可以直接使用,這件元件是由先前所介紹的那5個控制項所擴充而成
1. 下載
一樣至 http://ajax.asp.net/ 點選 Download ASP.NET AJAX v1.0 後出現以下畫面
點選 Download the ControlToolKit
2.新增至工具箱 加入索引 選擇項目 瀏覽 選擇剛剛下載的檔案裡位於 SampleWebSite\bin 中的 AjaxControlToolKit.dll
成功後工具箱將出現34種擴充元件可以使用
列舉幾個元件進行解說
1.TextBox 自動完成 (範例 AutoComplete.aspx)
AutoCompleteExtender
屬性:TargetControlID = 要被設定的TextBox 的ID
ServiceMethod = 後端所使用的Web Service( 或PageMethod)
ServicePath = WebService 的位置 , 不設定會自動判定使用 PageMethod
MinimumPrefixLength = 至少輸入多少字元後動作
CompletionInterval = 輸入多久後執行WebService的延遲時間(毫秒)
EnableCaching = 是否啟用 Caching
CompletionSetCount = 要回傳顯示的 item數
範例重點解說:
protected void Page_Load(object sender, EventArgs e) {
//設定 TargetControlID
AutoCompleteExtender1.TargetControlID = this.TextBox1.ID;
//輸入的字元長度
AutoCompleteExtender1.MinimumPrefixLength = 1;
//啟用Caching
AutoCompleteExtender1.EnableCaching = true;
//顯示的item數
AutoCompleteExtender1.CompletionSetCount = 15; //最多15筆
AutoCompleteExtender1.ServiceMethod = "GetEmailList";
}
//pageMethod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static String[] GetEmailList(String prefixText,int count) {
//prefixText =輸入的字串 , count 要回傳的數目
//連結DB做過濾
String Constr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + @"D:\研討會Ajax\SolutionExp\Example2\DB\mail.mdb";
String sql = "select Top "+ count +" * from mail where mail like '"+ prefixText.Trim() +"%' order by mail";//取得mail清單
OleDbConnection conn = new OleDbConnection(Constr);
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataTable dt = new DataTable();
da.Fill(dt);
String[] data = new string[dt.Rows.Count];
for (int i = 0; i < data.Length; i++) {
DataRow row = dt.Rows[i];
data[i] = row["mail"].ToString(); //取出mail
}
return data; //回傳String Array
}
2.自由拖曳panel(範例 DragPanel.aspx)
DragPanelExtender
屬性:TargetControlID = 要被拖曳的Panel 的ID
DragHandleID = 觸發拖曳事件的panel ID
*DragHandle 和 TargetControl 可為相同panel , 如不一樣,DragHandle的panel必須建立於TargetControl的panel 中
範例重點解說:
protected void Page_Load(object sender, EventArgs e) {
DragPanelExtender1.TargetControlID = this.Panel1.ID; // 要移動的panel;
DragPanelExtender1.DragHandleID = this.Panel2.ID;//觸發移動事件的panel;
this.Panel1.Style["cursor"] = "hand"; //滑鼠移到panel2 後游標變 成 hand
}
3.可拖曳放大縮小的網頁物件(範例 ResizableControl.aspx)
ResizableControl
屬性:
TargetControllID = 要改變大小的控制項
HandleCssClass = 拖曳點CSS設定
ResizableCssClass = 拖曳中的CSS設定
MinimunWidth = 拖曳時可接受的最小寬度
MinimunHeight = 拖曳時可接受的最小高度
MaxmumWidth = 拖曳時可接受的最大寬度
MaxmumHeight = 拖曳時可接受的最大高度
OnClientResize = 拖曳後要執行的javascript
OnClientResizing = 拖曳中要執行的javascript
OnClientResizeBegin = 拖曳前要執行的 javascript
HandleOffsetX = 拖曳點於物件右下角的X座標
HandleOffsetY = 拖曳點於物件右下角的Y座標
範例重點解說:
Css
<style type="text/css">
/* ResizableControl */
.frameImage
{
/* panel(圖片)大小 */
width:180px;
height:130px;
overflow:hidden;
float:left;
padding:3px;
}
.handleImage
{
/* 可拖曳圖示 */
width:15px;
height:16px;
background-image:url(Image/HandleHand.png);
overflow:hidden;
cursor:se-resize;
}
.resizingImage
{
padding:0px;
border-style:solid;
border-width:3px;
border-color:#B4D35D;
}
Javascript 抓取物件(panel1)大小 於Lable1中顯示
<script>
function onOK(){
$get('Label1').innerHTML=$get('Panel1').style.height + ',' + $get('Panel1').style.width;
}
</script>
主要程式碼
protected void Page_Load(object sender, EventArgs e) {
//拖曳圖示
ResizableControlExtender1.HandleCssClass = "handleImage";
//拖曳中的圖示
ResizableControlExtender1.ResizableCssClass = "resiaingImage";
//設定目標控制項
ResizableControlExtender1.TargetControlID = Panel1.ID;
//javascript function OnOK
ResizableControlExtender1.OnClientResize = "onOK";
//avascript function OnOK
ResizableControlExtender1.OnClientResizing = "onOK";
//最小高度
ResizableControlExtender1.MinimumHeight = 100;
//最小寬度
ResizableControlExtender1.MinimumWidth = 100;
}
4.Asp.net 2.0 Ajax應用 電子地圖
顯示頁面:DemoMap.aspx
處理頁面:GetMap.aspx
DemoMap.asp 程式碼
Javascript 在處理 拖曳panel 座標
<script type="text/javascript">
//位移變數
var offsetX,offsetY,startX,startY;
var isMoving; //開始移動Flag
function _start(){
//設定開始移動
isMoving=true;
//紀錄起點
startX=event.x;
startY=event.y;
startY=startY+17;
}
function _move(){
//如果在移動中模式
if (isMoving==true){
//移動
offsetX=event.x-startX;
offsetY=event.y-startY;
//設定圖檔位置
$get('Image1').style.left=10+(offsetX);
$get('Image1').style.top=130+(offsetY);
}
}
function _end(){
//如果在移動中模式
if (isMoving==true){
//設定處理完畢
isMoving=false;
//計算調整位移
offsetX=-(event.x-startX);
offsetY=-(event.y-startY);
offsetY= offsetY-17;
//以計算出的位移重新載入地圖
if (offsetX!=0 && offsetY!=0)
$get('Image1').src='GetMap.aspx?offsetX='+offsetX+'&offsetY='+offsetY+'&width=500&height=500';
$get('Image1').style.left=10;
$get('Image1').style.top=110;
}
}
</script>
DemoMap.aspx.cs
此function為在CS檔中直接定義 aspx中Panel_phantom 的Style 與javascrip操作事件
private void MakePhantom() {
Panel_phantom.Style["filter"] = "alpha(opacity=1);";
Panel_phantom.Style["cursor"] = "hand";
Panel_phantom.Style["position"] = "absolute";
Panel_phantom.Style["left"] = "15";
Panel_phantom.Style["top"] = "110";
Panel_phantom.Attributes["onmousedown"] = "_start();";
Panel_phantom.Attributes["onmouseup"] = "_end();";
Panel_phantom.Attributes["onmouseleave"] = "_end();";
Panel_phantom.Attributes["onmousemove"] = "_move();";
}
MapGotoXY 為 取得物件 Image1 的圖片來源 呼叫 GetMap.aspx 加上參數處理後,輸出所要顯示的圖片區塊
private void MapGotoXY(String x, String y) {
Image1.ImageUrl = "GetMap.aspx?x=" + x + "&y=" + y + "&width=500&height=500";
txb_x.Text = x ;
txb_y.Text = y ;
//設定拖曳用的Panel機制
MakePhantom();
}//MapGotoXY
GetMap.aspx
主要處理 地圖的顯示座標
protected void Page_Load(object sender, EventArgs e) {
//Image 的x,y 座標
int x =Convert.ToInt32(Request.QueryString["x"]);
int y =Convert.ToInt32( Request.QueryString["y"]);
//移動的 x,y座標
int offsetX = Convert.ToInt32(Request.QueryString["offsetX"]);
int offsetY = Convert.ToInt32(Request.QueryString["offsetY"]);
//地圖寬高
int width = Convert.ToInt32(Request.QueryString["width"]);
int height= Convert.ToInt32(Request.QueryString["height"]);
Bitmap bmp ;
Bitmap retbmp;
//讀入檔案
String ImgPath = Path.GetDirectoryName(Request.PhysicalPath) + @"\Image\tw.jpg";
bmp = new Bitmap(ImgPath);
if (x == 0 && y == 0 && offsetX != 0 && offsetY != 0) {
x = Convert.ToInt32(Session["_LastX"]) + offsetX;
y = Convert.ToInt32(Session["_LastY"])+ offsetY;
}
//防呆
if (x < 1) x = 1;
if (y < 1) y = 1;
if (x + width > bmp.Width) x = bmp.Width - width;
if (y + height > bmp.Height) y = bmp.Height - height;
//記錄 X,Y 座標
Session["_LastX"] = x;
Session["_LastY"] = y;
//宣告 GetMap 的輸出格式
Context.Response.ContentType= "image/Jpeg";
Context.Response.BufferOutput = false;
//建立矩形
Rectangle rect = new Rectangle(x, y, width, height);
retbmp = bmp.Clone(rect, bmp.PixelFormat); //取得圖片區塊
//處理圖形品質
System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.ImageCodecInfo ici = null;
//找出Encoder
foreach( System.Drawing.Imaging.ImageCodecInfo codec in codecs){
if( codec.MimeType == "image/jpeg") {
ici = codec;
}
}
//參數 - 高品質圖檔
System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters();
ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Convert.ToInt64(100));
retbmp.Save(Context.Response.OutputStream, ici, ep); //儲存
bmp.Dispose(); //釋放
retbmp.Dispose(); //釋放
Context.Response.End();//結束
}
5. 建立 統計圖
程式碼請參考
Chart..aspx
LineChart.cs
Chart..aspx主要顯示頁
LineChart.cs 為建立統計圖-點線圖的主要程式
輸出的圖 配合拖曳標籤可以自由移動圖表(使用DragPanelExtender)
如下方圖示
6. Ajax Excel圖表
程式碼過多 請參考
Excel_Demo.aspx
ExcelTable.cs
LineChart.cs
Excel_Demo.aspx 為主要顯示頁
背後處理程式有 ExcelTable.cs 與 LineChart.cs
ExcelTable.cs 提供3個funtion
1. reDrawExcelTable – 用來建立 table物件配合Javascript讓user感覺很像Excel
2. ExportDataTable –將Table轉化成DataTable提供給LineChart.cs
使LineChart 繪製圖片
3. SetValue – 初始化設定欄位的值
下圖為執行結果
Asp.Net2.0 配合 Ajax1.0 套件可以讓開發人員短時間之內,建出效果不錯的網頁,擴充元件讓頁面上只留下元件使用的標籤,除了微軟提供出的34項免費的基本元件可以使用外,也可以自行建立擴充元件 (Extender) , 至於要如何建立自訂的擴充元件,因為該功能步驟繁雜,等待小弟研究透徹後 ,有機會再向各位解說。
我的雲端生活網 - Life+
Sunday, June 24, 2007
Tuesday, June 5, 2007
socket 程式應該注意的參數
這幾天再寫jabber component 時發生一個奇怪的問題, 伺服器與component 固定一段時間就會終止通訊,然而連線此時還是存在的,伺服器或客乎端都沒有當掉,而且一般的jabber client 連接在上面也沒有問題,惟獨自己實做的server與client 無法通訊,後來發現;幾個socket 重要的參數,當client需要樣長時間連線時這些參數格外重要:
setsockopt SOL_SOCKET, SO_KEEPALIVE
setsockopt IPPROTO_TCP, TCP_KEEPIDLE
setsockopt IPPROTO_TCP, TCP_KEEPCNT
setsockopt IPPROTO_TCP, TCP_KEEPINTVL
程式再加了這些tcp 參數設定後,症狀完全消失
setsockopt SOL_SOCKET, SO_KEEPALIVE
setsockopt IPPROTO_TCP, TCP_KEEPIDLE
setsockopt IPPROTO_TCP, TCP_KEEPCNT
setsockopt IPPROTO_TCP, TCP_KEEPINTVL
程式再加了這些tcp 參數設定後,症狀完全消失
Saturday, May 26, 2007
perl v5.10 的相關資訊
http://pugs.blogs.com/talks/osdctw2007-perl510.pdf
看來這個承先啟後的版本做了不少的改變,在這些改變中,呵呵...台灣還佔有一席之地
看來這個承先啟後的版本做了不少的改變,在這些改變中,呵呵...台灣還佔有一席之地
Saturday, May 19, 2007
spamassassin v3.2 已釋出
其中比較有趣的是
1.
Mail::SpamAssassin::Spamd::Apache2 -- mod_perl2 module, implementing spamd as a mod_perl module, contributed as a Google Summer of Code project by Radoslaw Zielinski.
沒錯apache2 已不像過去,只是一個web server,他可以在上面發展其他的protocol,除了之前看過的smtp/ftp現在又多了spamd,但之前在apache2 上開發 lprd protocol 卻發現他的效率似乎沒有比自己寫伺服器來的好,至於穩不穩定,可能要有實際的數據支持
2.
sa-compile: compilation of SpamAssassin rules into a fast parallel-matching DFA, implemented in native code
這個技術我還沒時間仔細去trace,不過他應該是將spamassassin 使用的rules, 透過這個工具轉成c , 然後透過 xs 讓perl 來使用,這應該很有研究價值
1.
Mail::SpamAssassin::Spamd::Apache2 -- mod_perl2 module, implementing spamd as a mod_perl module, contributed as a Google Summer of Code project by Radoslaw Zielinski.
沒錯apache2 已不像過去,只是一個web server,他可以在上面發展其他的protocol,除了之前看過的smtp/ftp現在又多了spamd,但之前在apache2 上開發 lprd protocol 卻發現他的效率似乎沒有比自己寫伺服器來的好,至於穩不穩定,可能要有實際的數據支持
2.
sa-compile: compilation of SpamAssassin rules into a fast parallel-matching DFA, implemented in native code
這個技術我還沒時間仔細去trace,不過他應該是將spamassassin 使用的rules, 透過這個工具轉成c , 然後透過 xs 讓perl 來使用,這應該很有研究價值
Monday, April 30, 2007
xmpp 中文翻譯計畫 網站
http://wiki.jabbercn.org/space/start
另一個不錯的相關網站
http://hi.baidu.com/jabber/blog/category/Jep
iq:roster 的交易過程真是複雜的可以
http://64.233.179.104/translate_c?hl=zh-TW&sl=zh-CN&u=http://www.linuxboy.net/jabber/004.html&prev=/search%3Fq%3Diq:roster%26complete%3D1%26hl%3Dzh-TW%26pwst%3D1
另一個不錯的相關網站
http://hi.baidu.com/jabber/blog/category/Jep
iq:roster 的交易過程真是複雜的可以
http://64.233.179.104/translate_c?hl=zh-TW&sl=zh-CN&u=http://www.linuxboy.net/jabber/004.html&prev=/search%3Fq%3Diq:roster%26complete%3D1%26hl%3Dzh-TW%26pwst%3D1
Saturday, April 28, 2007
Concurrent Programming 相關報告
一. 我會接觸Erlang的緣由
1.RFID Middleware

2.jabber (xml::stream http://zh.wikipedia.org/wiki/Jabber)
3.ejabber (http://www.process-one.net/en/ )
二. 現在的商業環境(web server)所面臨的問題
1.連線的數量不斷的攀升
2.連線的時間很長
傳統上httpd 使用Prefork的方式來解決,短時間時密集連線的問題,在現在的環境愈到了嚴重的挑戰,比如: HTTP_Streaming、Server Push、COMET 這些需要長時間連線的架構,使得httpd 能夠服務的連線變少了,而fork process 最大的問題是,他所需要佔用記憶體的空間過於龐大,於是其他的伺服器架構崛起(lighthttpd ghttpd …)
The C10K problem( http://www.kegel.com/c10k.html )
It's time for web servers to handle ten thousand clients simultaneously, don't you think? After all, the web is a big place now.
And computers are big, too. You can buy a 1000MHz machine with 2 gigabytes of RAM and an 1000Mbit/sec Ethernet card for $1200 or so. Let's see - at 20000 clients, that's 50KHz, 100Kbytes, and 50Kbits/sec per client. It shouldn't take any more horsepower than that to take four kilobytes from the disk and send them to the network once a second for each of twenty thousand clients. (That works out to $0.08 per client, by the way. Those $100/client licensing fees some operating systems charge are starting to look a little heavy!) So hardware is no longer the bottleneck???
三. Concurrent Programming
1. fork
原始的程式
(程式+資料) --fork(複製一份)(程式+資料)
當程式fork 後,child 繼承原來的資料,此後彼此不相關,如果要傳遞資訊,需要使用pipe sharememory 或是 unix socket 來做資料交換
2. thread
事實上在Linux 系統下,執行緒只是一個light weight process:Linux 核心是以fork() system call 來產生一個新的行程(process),而執行緒是以clone() system call 產生的。fork()和clone()的差別只是在clone()可以指定和父行程共用的資源有哪些,當所有資源都和父行程共用時就相當於一個執行緒了。因為Thread 的使用會讓子父行程共用資源,因此非常容易引發dead lock / race condition …這類的問題
3. lightweight Threads ( http://www.defmacro.org/ramblings/concurrency.html)
Erlang process 是一個輕量級的Thread,因此他可以非常輕易的去開啟或是結束且快速在彼此做切換,因為掀開他的底層,他只是一個簡單的function罷了,process節省了大量的context switching浪費僅在一些function上做切換的動作(Erlang 的Thread 是 vm level thread)
這份文件簡單的提到了Erlang的概觀
http://mirror.linux.org.au/pub/linux.conf.au/2007/video/talks
/252.pdf
四. Erlang ( http://www.erlang.org/ )
1.以下是 about Erlang 對他自己的簡述
Erlang is a programming language which has many features more commonly associated with an operating system than with a programming language: concurrent processes, scheduling, memory management, distribution, networking, etc.
The initial open-source Erlang release contains the implementation of Erlang, as well as a large part of Ericsson's middleware for building distributed high-availability systems.
Erlang is characterized by the following features:
Concurrency - Erlang has extremely lightweight processes whose memory requirements can vary dynamically. Processes have no shared memory and communicate by asynchronous message passing. Erlang supports applications with very large numbers of concurrent processes. No requirements for concurrency are placed on the host operating system.
Distribution - Erlang is designed to be run in a distributed environment. An Erlang virtual machine is called an Erlang node. A distributed Erlang system is a network of Erlang nodes (typically one per processor). An Erlang node can create parallel processes running on other nodes, which perhaps use other operating systems. Processes residing on different nodes communicate in exactly the same was as processes residing on the same node.
Soft real-time - Erlang supports programming "soft" real-time systems, which require response times in the order of milliseconds. Long garbage collection delays in such systems are unacceptable, so Erlang uses incremental garbage collection techniques.
Hot code upgrade - Many systems cannot be stopped for software maintenance. Erlang allows program code to be changed in a running system. Old code can be phased out and replaced by new code. During the transition, both old code and new code can coexist. It is thus possible to install bug fixes and upgrades in a running system without disturbing its operation.
Incremental code loading - Users can control in detail how code is loaded. In embedded systems, all code is usually loaded at boot time. In development systems, code is loaded when it is needed, even when the system is running. If testing uncovers bugs, only the buggy code need be replaced.
External interfaces - Erlang processes communicate with the outside world using the same message passing mechanism as used between Erlang processes. This mechanism is used for communication with the host operating system and for interaction with programs written in other languages. If required for reasons of efficiency, a special version of this concept allows e.g. C programs to be directly linked into the Erlang runtime system.
2.Erlang 語言上的概觀
書籍: ( http://pragmaticprogrammer.com/titles/jaerlang/index.html )
[ Sequential Erlang ]
Exam1:
Consider the factorial function N! defined by:
N!=N*(N-1) when N>0
N!=1 when N=0
-module(math1).
-export([fac/1]).
fac(N) when N > 0 -> N * fac(N-1);
fac(0)-> 1.
Exam2:
-module(math2).
-export([sum1/1, sum2/1]).
sum1([H T]) -> H + sum1(T);
sum1([]) -> 0.
sum2(L) -> sum2(L, 0).
sum2([], N) -> N;
sum2([H T], N) -> sum2(T, H+N).
[ Concurrency Programming ]
Exam3:
-module(concurrency).
-export([start/0, say /2]).
say (What, 0) ->
done;
say (What, Times) ->
io:format("~p~n", [What]),
say_something(What, Times - 1).
start() ->
spawn(tut14, say, [hello, 3]),
spawn(tut14, say, [goodbye, 3]).
Exam4:
-module(area_server).
-export([loop/0]).
loop() ->
receive
{rectangle, Width, Ht} ->
io:format("Area of rectangle is ~p~n",[Width * Ht]),
loop();
{circle, R} ->
io:format("Area of circle is ~p~n", [3.14159 * R * R]),
loop();
Other ->
io:format("I don't know what the area of a ~p is ~n",[Other]),
loop()
end.
We can create a process which evaluates loop/0 in the shell:
Pid = spawn(area_server,loop,[]).
Pid ! {rectangle, 6, 10}.
Pid ! {circle, 23}.
Pid ! {triangle,2,4,5}.
4. Erlang –style process or event-based model for actors ( http://lambda-the-ultimate.org/node/1615 )
( http://lamp.epfl.ch/~phaller/doc/haller07coord.pdf )
Message passing
Each process has its own input queue for messages it receives. New messages received are put at the end of the queue. When a process executes a receive, the first message in the queue is matched against the first pattern in the receive, if this matches, the message is removed from the queue and the actions corresponding to the the pattern are executed.
However, if the first pattern does not match, the second pattern is tested, if this matches the message is removed from the queue and the actions corresponding to the second pattern are executed. If the second pattern does not match the third is tried and so on until there are no more pattern to test. If there are no more patterns to test, the first message is kept in the queue and we try the second message instead. If this matches any pattern, the appropriate actions are executed and the second message is removed from the queue (keeping the first message and any other messages in the queue). If the second message does not match we try the third message and so on until we reach the end of the queue. If we reach the end of the queue, the process blocks (stops execution) and waits until a new message is received and this procedure is repeated.
Of course the Erlang implementation is "clever" and minimizes the number of times each message is tested against the patterns in each receive.
五. Erlang相關資源
Website:
Open Source Erlang
http://www.erlang.org
http://www.process-one.net/en/projects/
Mail List:
Erlang-questions -- Erlang/OTP discussions
http://www.erlang.org/mailman/listinfo/erlang-questions
BOOK:
Concurrent programming in Erlang
http://www.erlang.org/download/erlang-book-part1.pdf
Programming Erlang Software for a Concurrent World
http://pragmaticprogrammer.com/titles/jaerlang/index.html
1.RFID Middleware
2.jabber (xml::stream http://zh.wikipedia.org/wiki/Jabber)
3.ejabber (http://www.process-one.net/en/ )
二. 現在的商業環境(web server)所面臨的問題
1.連線的數量不斷的攀升
2.連線的時間很長
傳統上httpd 使用Prefork的方式來解決,短時間時密集連線的問題,在現在的環境愈到了嚴重的挑戰,比如: HTTP_Streaming、Server Push、COMET 這些需要長時間連線的架構,使得httpd 能夠服務的連線變少了,而fork process 最大的問題是,他所需要佔用記憶體的空間過於龐大,於是其他的伺服器架構崛起(lighthttpd ghttpd …)
The C10K problem( http://www.kegel.com/c10k.html )
It's time for web servers to handle ten thousand clients simultaneously, don't you think? After all, the web is a big place now.
And computers are big, too. You can buy a 1000MHz machine with 2 gigabytes of RAM and an 1000Mbit/sec Ethernet card for $1200 or so. Let's see - at 20000 clients, that's 50KHz, 100Kbytes, and 50Kbits/sec per client. It shouldn't take any more horsepower than that to take four kilobytes from the disk and send them to the network once a second for each of twenty thousand clients. (That works out to $0.08 per client, by the way. Those $100/client licensing fees some operating systems charge are starting to look a little heavy!) So hardware is no longer the bottleneck???
三. Concurrent Programming
1. fork
原始的程式
(程式+資料) --fork(複製一份)(程式+資料)
當程式fork 後,child 繼承原來的資料,此後彼此不相關,如果要傳遞資訊,需要使用pipe sharememory 或是 unix socket 來做資料交換
2. thread
事實上在Linux 系統下,執行緒只是一個light weight process:Linux 核心是以fork() system call 來產生一個新的行程(process),而執行緒是以clone() system call 產生的。fork()和clone()的差別只是在clone()可以指定和父行程共用的資源有哪些,當所有資源都和父行程共用時就相當於一個執行緒了。因為Thread 的使用會讓子父行程共用資源,因此非常容易引發dead lock / race condition …這類的問題
3. lightweight Threads ( http://www.defmacro.org/ramblings/concurrency.html)
Erlang process 是一個輕量級的Thread,因此他可以非常輕易的去開啟或是結束且快速在彼此做切換,因為掀開他的底層,他只是一個簡單的function罷了,process節省了大量的context switching浪費僅在一些function上做切換的動作(Erlang 的Thread 是 vm level thread)
這份文件簡單的提到了Erlang的概觀
http://mirror.linux.org.au/pub/linux.conf.au/2007/video/talks
/252.pdf
四. Erlang ( http://www.erlang.org/ )
1.以下是 about Erlang 對他自己的簡述
Erlang is a programming language which has many features more commonly associated with an operating system than with a programming language: concurrent processes, scheduling, memory management, distribution, networking, etc.
The initial open-source Erlang release contains the implementation of Erlang, as well as a large part of Ericsson's middleware for building distributed high-availability systems.
Erlang is characterized by the following features:
Concurrency - Erlang has extremely lightweight processes whose memory requirements can vary dynamically. Processes have no shared memory and communicate by asynchronous message passing. Erlang supports applications with very large numbers of concurrent processes. No requirements for concurrency are placed on the host operating system.
Distribution - Erlang is designed to be run in a distributed environment. An Erlang virtual machine is called an Erlang node. A distributed Erlang system is a network of Erlang nodes (typically one per processor). An Erlang node can create parallel processes running on other nodes, which perhaps use other operating systems. Processes residing on different nodes communicate in exactly the same was as processes residing on the same node.
Soft real-time - Erlang supports programming "soft" real-time systems, which require response times in the order of milliseconds. Long garbage collection delays in such systems are unacceptable, so Erlang uses incremental garbage collection techniques.
Hot code upgrade - Many systems cannot be stopped for software maintenance. Erlang allows program code to be changed in a running system. Old code can be phased out and replaced by new code. During the transition, both old code and new code can coexist. It is thus possible to install bug fixes and upgrades in a running system without disturbing its operation.
Incremental code loading - Users can control in detail how code is loaded. In embedded systems, all code is usually loaded at boot time. In development systems, code is loaded when it is needed, even when the system is running. If testing uncovers bugs, only the buggy code need be replaced.
External interfaces - Erlang processes communicate with the outside world using the same message passing mechanism as used between Erlang processes. This mechanism is used for communication with the host operating system and for interaction with programs written in other languages. If required for reasons of efficiency, a special version of this concept allows e.g. C programs to be directly linked into the Erlang runtime system.
2.Erlang 語言上的概觀
書籍: ( http://pragmaticprogrammer.com/titles/jaerlang/index.html )
[ Sequential Erlang ]
Exam1:
Consider the factorial function N! defined by:
N!=N*(N-1) when N>0
N!=1 when N=0
-module(math1).
-export([fac/1]).
fac(N) when N > 0 -> N * fac(N-1);
fac(0)-> 1.
Exam2:
-module(math2).
-export([sum1/1, sum2/1]).
sum1([H T]) -> H + sum1(T);
sum1([]) -> 0.
sum2(L) -> sum2(L, 0).
sum2([], N) -> N;
sum2([H T], N) -> sum2(T, H+N).
[ Concurrency Programming ]
Exam3:
-module(concurrency).
-export([start/0, say /2]).
say (What, 0) ->
done;
say (What, Times) ->
io:format("~p~n", [What]),
say_something(What, Times - 1).
start() ->
spawn(tut14, say, [hello, 3]),
spawn(tut14, say, [goodbye, 3]).
Exam4:
-module(area_server).
-export([loop/0]).
loop() ->
receive
{rectangle, Width, Ht} ->
io:format("Area of rectangle is ~p~n",[Width * Ht]),
loop();
{circle, R} ->
io:format("Area of circle is ~p~n", [3.14159 * R * R]),
loop();
Other ->
io:format("I don't know what the area of a ~p is ~n",[Other]),
loop()
end.
We can create a process which evaluates loop/0 in the shell:
Pid = spawn(area_server,loop,[]).
Pid ! {rectangle, 6, 10}.
Pid ! {circle, 23}.
Pid ! {triangle,2,4,5}.
4. Erlang –style process or event-based model for actors ( http://lambda-the-ultimate.org/node/1615 )
( http://lamp.epfl.ch/~phaller/doc/haller07coord.pdf )
Message passing
Each process has its own input queue for messages it receives. New messages received are put at the end of the queue. When a process executes a receive, the first message in the queue is matched against the first pattern in the receive, if this matches, the message is removed from the queue and the actions corresponding to the the pattern are executed.
However, if the first pattern does not match, the second pattern is tested, if this matches the message is removed from the queue and the actions corresponding to the second pattern are executed. If the second pattern does not match the third is tried and so on until there are no more pattern to test. If there are no more patterns to test, the first message is kept in the queue and we try the second message instead. If this matches any pattern, the appropriate actions are executed and the second message is removed from the queue (keeping the first message and any other messages in the queue). If the second message does not match we try the third message and so on until we reach the end of the queue. If we reach the end of the queue, the process blocks (stops execution) and waits until a new message is received and this procedure is repeated.
Of course the Erlang implementation is "clever" and minimizes the number of times each message is tested against the patterns in each receive.
五. Erlang相關資源
Website:
Open Source Erlang
http://www.erlang.org
http://www.process-one.net/en/projects/
Mail List:
Erlang-questions -- Erlang/OTP discussions
http://www.erlang.org/mailman/listinfo/erlang-questions
BOOK:
Concurrent programming in Erlang
http://www.erlang.org/download/erlang-book-part1.pdf
Programming Erlang Software for a Concurrent World
http://pragmaticprogrammer.com/titles/jaerlang/index.html
Labels:
active rfid,
Concurrent Programming,
Erlang,
RFID,
RFID MIDDLEWARE,
主動式rfid,
微程式技術研討會,
微程式資訊股份有限公司,
技術研討會
Tuesday, April 24, 2007
xmpp 實做的分享
最近在寫jabber server, jabber 是建構在xmpp protocol 上的一個IM,因為RFC的規格制定曠日費時,所以;jabber 以xmpp 為基礎,自己又定義了約200 個協定XEP-0001~0214,而 xmpp 主要由五個protocol所組成,分別是RFC-3920~3923 RFC-4622
我目前的進度已經可以讓像 Exodus or Pandion(IM Client) 連接上我自己實做的jabber server,預計下星期我就能讓im client 直接在上面talk,且訂閱彼此的狀態...在寫的過程成中越來越覺得他的複雜,其實,這大概是我目前寫過最複雜的伺服器,不過有一點心得可以先分享給大家,其實有一些人有一個疑問,jabber長的像什麼? 如果我們撇開他在IM的實做(處理訊息的傳遞也是一種運算資源),我們可以把它看成是一家公司,一家公司會有他對客戶的服務,而當產品要製作時,它需要資源,需要應徵人員,每個應徵的人員需要依照公司的制度來運行(component plug-in),每個人員應徵後需要報到,然後正式工作,依照給個人的專業知識分派工作 ....循環不已,當新的產品要製作時,這個公司可以再應徵新的 不同專業領域的資源,而且可以重新制定新的工作規則...而公司組織裡的這些運行其實都是靠制度,而這個制度相對於jabber 就是他的protocol,所以我把xmpp形容成是一個資源/運算的分散者,因此他可以建構一個基本的Grid Computing 環境,把每個運算工作分散到無限台機器上....如果你要問他可以做什麼? 事實上在jabber 的protocol 裡幾乎定義了絕大部分
的應用,voip 影音...,所有的運算資源都可以在事後 plug in 進去,google_talk 所實做的部份可能還不到整個jabber 的1/20,由此;我們可以看出他的規模/擴充性之大... 總之把他想成是一個有組織的公司,只是公司的規模有大有小罷了,xmpp 的工作資源分配真的跟這個描述很像,有機會自己實做一次體會一下囉!
我目前的進度已經可以讓像 Exodus or Pandion(IM Client) 連接上我自己實做的jabber server,預計下星期我就能讓im client 直接在上面talk,且訂閱彼此的狀態...在寫的過程成中越來越覺得他的複雜,其實,這大概是我目前寫過最複雜的伺服器,不過有一點心得可以先分享給大家,其實有一些人有一個疑問,jabber長的像什麼? 如果我們撇開他在IM的實做(處理訊息的傳遞也是一種運算資源),我們可以把它看成是一家公司,一家公司會有他對客戶的服務,而當產品要製作時,它需要資源,需要應徵人員,每個應徵的人員需要依照公司的制度來運行(component plug-in),每個人員應徵後需要報到,然後正式工作,依照給個人的專業知識分派工作 ....循環不已,當新的產品要製作時,這個公司可以再應徵新的 不同專業領域的資源,而且可以重新制定新的工作規則...而公司組織裡的這些運行其實都是靠制度,而這個制度相對於jabber 就是他的protocol,所以我把xmpp形容成是一個資源/運算的分散者,因此他可以建構一個基本的Grid Computing 環境,把每個運算工作分散到無限台機器上....如果你要問他可以做什麼? 事實上在jabber 的protocol 裡幾乎定義了絕大部分
的應用,voip 影音...,所有的運算資源都可以在事後 plug in 進去,google_talk 所實做的部份可能還不到整個jabber 的1/20,由此;我們可以看出他的規模/擴充性之大... 總之把他想成是一個有組織的公司,只是公司的規模有大有小罷了,xmpp 的工作資源分配真的跟這個描述很像,有機會自己實做一次體會一下囉!
Subscribe to:
Posts (Atom)