Python Tcp 服务器调用带参数的函数
我在寻找一种更好的方法来通过tcpclient调用带参数或不带参数的函数。目前似乎没有固定的方式。
我现在的做法是这样的。
在客户端,我发送一个字符串,比如:
server#broadcast#helloworld
然后在服务器端:
commands = []
data = self.request.recv(BUFF)
commands = data.split('#')
if commands[0] == 'server':
if commands[1] == 'stop':
serverStop()
if commands[1] == 'broadcast':
sendtoall(commands[2])
if commands[0] == 'application':
if commands[1] == 'doStuff':
doStuff(commands[2], commands[3])
从客户端我发送一个字符串,格式是命令#子命令#参数#参数,然后在服务器端把它拆分开来,调用相应的函数。这个方法可以用,但调用函数和检查错误的过程会很快变得冗余。
我想把错误检查放在服务器端。它应该能够处理带参数和不带参数的函数,并且支持任意数量的参数。
如果你有更好的方法来从客户端调用函数,请分享一下。感谢你的阅读。
2 个回答
1
为什么不使用RPC协议呢?在这种情况下,你就不需要解析字符串了。
这是服务器的代码
from SimpleXMLRPCServer import SimpleXMLRPCServer
def add(a, b):
return a+b
server = SimpleXMLRPCServer(("localhost", 1234))
print "Listening on port 1234..."
server.register_function(add, "add")
server.serve_forever()
这是客户端的代码
import xmlrpclib
print 'start'
proxy = xmlrpclib.ServerProxy("http://localhost:1234/")
print "3 + 4 is: %s" % str(proxy.add(3, 4))
1
你应该根据你想要实现的目标和你的网络协议来调整程序的结构。我假设你在这个例子中使用的是一种自定义的无状态协议。
commands = []
data = self.request.recv(BUFF)
commands = data.split('#')
process_commands(commands)
def process_commands(commands):
"""
Determines if this is a server or application command.
"""
if commands[0] == 'server':
process_server_command(commands[1:])
if commands[0] == 'application':
process_application_command(commands[1:])
def process_server_command(commands):
"""
because I truncated the last list and removed it's 0 element we're
starting at the 0 position again in this function.
"""
if commands[0] == 'stop':
serverStop()
if commands[0] == 'broadcast':
sendtoall(commands[1])
def process_application_command(commands)
if commands[0] == 'doStuff':
doStuff(commands[1], commands[2])
这种结构去掉了嵌套的if语句,让你更容易看出代码的控制流程。这样也会让你添加try
except
块变得简单多了(如果你在使用普通的套接字,这个是必需的)。