我正在使用以下内容设置服务器:
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
发送命令和参数也很好。
我已经google了很多,并在客户端上找到了类似的内容:
def send_data(self, com, arg):
content={"command": com, "arg": arg}
return json.dumps(content)
def shreddingclient
如何接受命令,执行其他def
的参数?
(这是为了避免shreddingclient
将是一个巨大的if
/ elif
函数)
答案 0 :(得分:0)
假设您只是在询问了从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)
答案 1 :(得分:0)
您使用调度程序,快速示例如下:
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"