【问题标题】:How can i send empty terminal output from server to client?如何将空终端输出从服务器发送到客户端?
【发布时间】:2020-03-27 09:32:12
【问题描述】:

我正在尝试将 linux 命令从客户端发送到服务器并将服务器输出重新发送到客户端。我可以将所有命令发送到服务器,它们在服务器端工作,但是当我发送像“mkdir、rmdir 等”这样的命令时。这些命令在服务器端工作,但客户端无法接收终端输出消息。我认为这是因为实际上还没有输出消息,我的客户端卡住了,我必须重新启动它。

客户端:

    while True: 
 # message sent to server 

        s.send(message.encode('ascii')) 
        # messaga received from server 

        data = s.recv(1024) 
   # print the received message 
        # here it would be a reverse of sent message

        print('Received from the server :',str(data.decode('ascii'))) 
        # ask the client whether he wants to continue 

        ans = input('\nDo you want to continue(y/n) :') 
        if ans == 'y':
            message = input("enter message")
            continue
        else: 
            break

    # close the connection 
    s.close() 

服务器端:

while True:

        # data received from client

        data = c.recv(1024)
        if not data:
            print('Bye')
            break
        try:
            data_o = subprocess.check_output(data, shell=True)
        except subprocess.CalledProcessError as e:
            c.send(b'failed\n')
            print(e.output)
        #data_o = subprocess.Popen(["echo", data], stdout=subprocess.PIPE)

        print(type(data_o))
        c.send(data_o)

示例输出:

感谢您的帮助

【问题讨论】:

标签: python linux client-server


【解决方案1】:

由于输出是一个长度为 0 的字节对象,所以什么都没有发送,但是您的客户端一直在等待答案。一个简单的解决方案是只发送一个字符串,如“没有给出输出”。 为防止在发送命令 echo no output was given 时出现混淆,您可以为每个响应添加前缀。

类似这样的:

if data[0:prefix_len]== success_prefix:
    print(data[prefix_len:]
elif data[0:prefix_len] == empty_prefix:
    print("command had no output")


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2012-06-04
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多