首页 > 解决方案 > 如何将空终端输出从服务器发送到客户端?

问题描述

我正在尝试将 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)

示例输出: 在此处输入图像描述

感谢您的帮助

标签: pythonlinuxclient-server

解决方案


由于输出是一个长度为 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")



推荐阅读