主页 > 知识库 > 网络编程 > PHP >
栏目列表

PHP

PHP或Python调用C++实现的服务器(2)

来源:互联网 作者:PHPer 发表于:2009-09-29 11:02  点击:
else: print +----------------------------------------------------------- print | put key value - Put (key, value) print | get key - Get value of a key print | q - Quit print +------------------------

else:
print "+-----------------------------------------------------------"
print "| put <key> <value> - Put (key, value)"
print "| get <key> - Get value of a key"
print "| q - Quit"
print "+-----------------------------------------------------------"

while True:

sys.stdout.write("\n> ")

input = sys.stdin.readline().split()
cmd = input[0]

if cmd == "get" or cmd == "g":
if len(input) < 2:
continue
key = int(input[1], 10)
ret = server.call(HashSever_get, key)
if ret[0] == pycerl.code_ok:
print "result:", ret[1]
else:
print "error:", ret[0]

elif cmd == "put" or cmd == "p":
if len(input) < 3:
continue
key = int(input[1], 10)
value = int(input[2], 10)
ret = server.call(HashSever_put, key, value)
if ret[0] == pycerl.code_ok:
print "ok!"
else:
print "error:", ret[0]

elif cmd == "q":
break

else:
print "unknown command!"

pycerl.thread_term()
HashSever_put = 1
HashSever_get = 2

import sys, pycerl

pycerl.thread_init()

server = pycerl.connect("localhost:8889", "HashServer")
if not server:
print "ERROR: Connect HashSever failed!"

else:
print "+-----------------------------------------------------------"
print "| put <key> <value> - Put (key, value)"
print "| get <key> - Get value of a key"
print "| q - Quit"
print "+-----------------------------------------------------------"

while True:

sys.stdout.write("\n> ")

input = sys.stdin.readline().split()
cmd = input[0]

if cmd == "get" or cmd == "g":
if len(input) < 2:
continue
key = int(input[1], 10)
ret = server.call(HashSever_get, key)
if ret[0] == pycerl.code_ok:
print "result:", ret[1]
else:
print "error:", ret[0]

elif cmd == "put" or cmd == "p":
if len(input) < 3:
continue
key = int(input[1], 10)
value = int(input[2], 10)
ret = server.call(HashSever_put, key, value)
if ret[0] == pycerl.code_ok:
print "ok!"
else:
print "error:", ret[0]

elif cmd == "q":
break

else:
print "unknown command!"

pycerl.thread_term()

值得注意的是,这里我们没有像C/C++一样,用一个编译器为SDL翻译生成PHP/Python的Proxy代码。这是动态语言的优势,哪怕没有Proxy,其代码仍然看起来相当优雅(不过话又说回来,其实C++也可以做到的,但是略损失些性能)。

有帮助
(0)
0%
没帮助
(0)
0%