我目前正在设置一个服务器,其中包含以下内容:
try:
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print time.ctime() + ' Connection from: ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(shreddingclient ,(conn,))
except KeyboardInterrupt:
print "Exiting gracefully anyway"
finally:
s.close()我还在想,能够向服务器def shredding client发送命令和参数也会很好。
我搜索了很多,并在客户端上找到了类似的东西。
def send_data(self, com, arg):
content={"command": com, "arg": arg}
return json.dumps(content)我的问题是:
def shreddingclient将如何接受命令,即执行其他def的参数?
(这是为了避免shreddingclient将是一个巨大的if/elif函数)
发布于 2016-02-23 21:50:29
假设您只要求在从json接收命令并将其解码为dict之后才发出命令,则可以使用另一个dict将命令名映射到实现这些命令的函数。在这里,msg是传递给shredderclient的解码消息dict。
def command1(msg):
print(msg['arg'])
def command2(msg):
print(msg['arg'])
dispatch_table = {'command1':command1, 'command2':command2}
def process_message(msg):
try:
cmd = dispatch_table[msg['command']]
except KeyError:
print('invalid command')
return None
cmd(msg)发布于 2016-02-23 21:52:13
如果使用dispatcher,一个简单的示例如下:
dispatcher = {'command_1': func_1,
'command_2': func_2,
...}当你收到数据时:
data = json.loads(content)
command = data['command']
args, kwargs = data['args'], data['kwargs']
try:
res = dispatcher[command](*args, **kwargs)
except KeyError:
print "Unknown command"https://stackoverflow.com/questions/35588680
复制相似问题