简体   繁体   English

while循环中的Python套接字recv数据未停止

[英]Python socket recv data in while loop not stopping

While im trying to recv data with a while loop the loop not stopping even when there is no data 当我尝试使用while loop来接收数据时,即使没有数据,循环也不会停止

import socket


class Connect:
    connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def __init__(self, server_ip, server_port):
        self.connect.connect((server_ip, server_port))

    def recv(self):
        data_ls = []
        while True:
            data = self.connect.recv(2048)
            if not data: # after getting the first data
                break #    Python wont come to this "if" so it wont break!

            data = data.decode('utf-8')
            data_ls.append(data)
        return data_ls

Because socket.recv is a blocking call. 因为socket.recv是阻塞调用。 This means that your program will be paused until the amount of data you asked for (2048 bytes) is available to receive. 这意味着您的程序将被暂停,直到您请求的数据量(2048字节)可以接收为止。

You can set a time limit on how long to wait for data: 您可以设置等待数据的时间限制:

socket.settimeout(seconds_to_wait_for_data)

Or, you can make the socket not block: 或者,您可以使套接字不阻塞:

sock.setblocking(False)

Note that under your current implementation, your code will probably busy wait for data to be available, potentially using more system resources than necessary. 请注意,在您当前的实现中,您的代码可能会忙于等待数据可用,从而可能使用比必要数量更多的系统资源。 You can prevent this by: 您可以通过以下方法防止这种情况:

  • looking for a signal for when there isn't any more data from the server at the start (such as a Content-Length header for HTTP) while setting a timeout (in case of network issues) 在设置超时时(在网络问题的情况下)在开始时寻找服务器何时没有更多数据的信号(例如HTTP的Content-Length标头)
  • using a library implementing a higher level protocol 使用实现更高级别协议的库

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

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