发送命令和参数到python套接字服务器

时间:2016-02-23 21:36:23

标签: python

我正在使用以下内容设置服务器

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函数)

2 个答案:

答案 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"