首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向python套接字服务器发送命令和参数

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

Stack Overflow用户
提问于 2016-02-23 21:36:22
回答 2查看 122关注 0票数 0

我目前正在设置一个服务器,其中包含以下内容:

代码语言:javascript
复制
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发送命令和参数也会很好。

我搜索了很多,并在客户端上找到了类似的东西。

代码语言:javascript
复制
def send_data(self, com, arg):
       content={"command": com, "arg": arg}
       return json.dumps(content)

我的问题是:

def shreddingclient将如何接受命令,即执行其他def的参数?

(这是为了避免shreddingclient将是一个巨大的if/elif函数)

EN

回答 2

Stack Overflow用户

发布于 2016-02-23 21:50:29

假设您只要求在从json接收命令并将其解码为dict之后才发出命令,则可以使用另一个dict将命令名映射到实现这些命令的函数。在这里,msg是传递给shredderclient的解码消息dict

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2016-02-23 21:52:13

如果使用dispatcher,一个简单的示例如下:

代码语言:javascript
复制
dispatcher = {'command_1': func_1,
              'command_2': func_2,
              ...}

当你收到数据时:

代码语言:javascript
复制
data = json.loads(content)
command = data['command']
args, kwargs = data['args'], data['kwargs']
try:
    res = dispatcher[command](*args, **kwargs)
except KeyError:
    print "Unknown command"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35588680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档