简体   繁体   English

Python-套接字行为异常?

[英]Python - Sockets behaving oddly?

I have a client / server application, and it is very basic. 我有一个客户端/服务器应用程序,这是非常基本的。 The client sends the server a message with information containing a file name, the server then creates this file in the server directory, the client will then proceed to send all the binary data from the file that the client chose to the server (and the server writes it into the newly formed file). 客户端向服务器发送一条消息,其中包含包含文件名的信息,然后服务器在服务器目录中创建此文件,然后客户端将继续将客户端选择的文件中的所有二进制数据发送到服务器(以及服务器)将其写入新形成的文件)。 The server then needs to run this file and send all output back to client. 然后,服务器需要运行此文件,并将所有输出发送回客户端。 It was working fine, until I hit this dead end and it keeps looping. 一切正常,直到我碰到了这个死胡同,然后一直循环播放。 Here's a simplified version of the code on the server: 这是服务器上代码的简化版本:

if data_received.startswith("COMMAND:run_file"): #client tells server to create new file
    #create file
    while True:
        #Get binary data from client
        #If data is blank break
        #Write data to new file
    #Close file
    #Open up new file using subprocess
    p = Popen("python " + data[17:], shell=True,stdin=PIPE,stdout=PIPE,stderr=STDOUT)
    print p.stdout.read() #Print output

Now whenever this code is run, the server will receive the binary data of the client's file fine, but then it will just sit there... waiting for something, and it is not waiting for a new command from the client (I know this much). 现在,无论何时运行此代码,服务器都会很好地接收客户端文件的二进制数据,但随后它将只坐在那里...等待某事,而不是在等待客户端的新命令(我知道许多)。 I am confused, so could someone spot the (possibly) very obvious mistake I've made somewhere? 我很困惑,所以有人可以发现我在某个地方犯的(可能)非常明显的错误吗?

Edit: 编辑:
I have found where it is getting stuck, and it is after 我发现它卡在哪里了

print p.stdout.read()

Now I have no clue why this is getting stuck. 现在我不知道为什么会卡住。

As said in my comment if the subprocess you start is Python, I would recommend to use the multiprocessing module. 如我的评论中所述,如果您启动的子进程是Python,则建议使用multiprocessing模块。

However, to answer your question I think stdout is buffered, and stdout.read() will only return when the sub-process ends. 但是,为回答您的问题,我认为stdout已缓冲,并且stdout.read()仅在子进程结束时返回。

The solution would be to use stdout.readline() instead of stdout.read() . 解决方案是使用stdout.readline()而不是stdout.read() Also, do not redirect stderr to PIPE if you are not reading stderr . 另外,如果您没有阅读stderr ,请不要将stderr重定向到PIPE

If you use conn.recv(1024) it will wait until it receives data. 如果使用conn.recv(1024),它将等待直到接收到数据。 And since you are in a while true loop, it will continuously try to receive data, if all the data is sent it doesn't receive anything (instead of 'blank data'). 而且,由于您处于“一会儿真实”循环中,因此它将连续尝试接收数据,如果发送了所有数据,它将什么也不会收到(而不是“空白数据”)。 Therefore, your 'if data is blank' is never true. 因此,您的“如果数据为空”永远不会正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM