CERL: 用PHP或Python来做服务器

到现在,关于CERL的故事终于看起来慢慢多起来了:

  • Erlang vs. CERL - CERL简介
  • 注释及文档的故事
  • CERL SDL 语法及类型系统
  • CERL: PHP或Python调用C++实现的服务器

之前我们已经谈到C++做高性能的服务器,然后PHP或Python作为前端,将服务展现给客户。这是一种比较正常的逻辑。今天的内容可能稍微偏门一点,谈谈基于CERL,用PHP或Python来做服务器。这在一定程度上有意义的,如果你原先就已经写了基于PHP或者Python的服务的话(或者服务本身的性能要求不高,而你更喜欢PHP或Python)。

 

用PHP写的HashServer(这个例子貌似我们举了很多次了)如下:

<?php define('HashSever_put', 1); define('HashSever_get', 2); if (!extension_loaded('php_cerl')) { if (!dl('php_cerl.' . PHP_SHLIB_SUFFIX)) die("ERROR: Cannot load php_cerl library!/n"); } if (!cerl_bind('localhost:8889')) die("ERROR: Bind failed!/n"); cerl_thread_init(); cerl_register('HashServer'); echo "HashServer (port:8889) starting ... ok!/n"; for (;;) { $mail = cerl_receive(); list($fid, $args) = $mail->decode(); echo "/nreceived: $fid - "; foreach ($args as $arg) echo "$arg "; if ($fid == HashSever_put) { list($key, $value) = $args; $dict[$key] = $value; $mail->reply(code_ok); } else if ($fid == HashSever_get) { list($key) = $args; @$value = $dict[$key]; if (isset($value)) $mail->reply(code_ok, $value); else $mail->reply(code_false); } else { $mail->default_handle(); } } cerl_thread_term(); ?>

 

用Python写的HashServer看起来是这样的:

HashSever_put = 1 HashSever_get = 2 import sys, pycerl if not pycerl.bind("localhost:8889"): print "ERROR: Bind failed!" else: pycerl.thread_init() pycerl.register("HashServer") print "HashServer (port:8889) starting ... ok!" dict = {} while True: mail = pycerl.receive() (fid, args) = mail.decode() print "received:", fid, "-", args if fid == HashSever_put: (key, value) = args dict[key] = value mail.reply(pycerl.code_ok) elif fid == HashSever_get: (key,) = args if key in dict: mail.reply(pycerl.code_ok, dict[key]) else: mail.reply(pycerl.code_false) else: mail.default_handle() pycerl.thread_term()

 

我们目前已经实现了3个语言的HashServer服务器(C++,PHP,Python),对应地也写了3个语言的HashClient。需要指出的是,这些HashServer和HashClient可以任意搭配使用,你可以想象这里面可以有9种可能。:) 当然多少种可能并不重要,重要的是,语言之间的隔阂消除了。以前你可能想的是,如何让C与Python交互,C与PHP交互,但是却很少会涉及Python与PHP交互。而CERL打破了这个界限。

 

当然,你可能会说,一些RPC(如DCOM、ICE等等)也致力于消除语言的隔阂。没错。不过关于这方面的对比,我始终要卖一个关子,要等到“CN Erlounge IV”上作详细的阐述。关于本次大会的详细内容,参阅:http://blog.csdn.net/xushiweizh/archive/2009/08/09/4428977.aspx

你可能感兴趣的:(thread,PHP,python,服务器,语言,extension)