【问题标题】:Unable to send data multiple requests in a single connection — socket error无法在单个连接中发送数据多个请求 - 套接字错误
【发布时间】:2013-08-13 05:12:16
【问题描述】:

这个问题来自我之前的问题。我需要一次将一些数据多次(在此特定示例中为 2 次)发送到服务器:

conn = httplib.HTTPSConnection("www.site.com")
conn.connect()
conn.putrequest("POST", path)
conn.putheader("Content-Type", "some type")
fake_total_size = total_size / 2  # split a file into 2 parts

conn.putheader("Content-Length", str(fake_total_size))
conn.endheaders()

chunk_size = fake_total_size
source_file = open(file_name)

#1 part
chunk = source_file.read(chunk_size)
conn.send(chunk)                         # ok!
response = conn.getresponse()
print response.read()                    # ok!

#2 part
chunk = source_file.read(chunk_size)
conn.send(chunk)                         # OPS! [Errno 32] Broken pipe
response = conn.getresponse()
print response.read()

source.close()

也就是说,我想在一个连接中发送多个请求而不关闭或重新创建它。

请注意,错误肯定不是因为服务器故障,而是因为 socket,但为什么呢?

如何消除错误?

更新

同样的错误:

#1 part
chunk = source_file.read(chunk_size)
conn.send(chunk)                         # ok!
 #response = conn.getresponse()
 #print response.read()

更新 2:

还是没有运气:

conn.putheader("Connection", "Keep-Alive")
#.........
chunck_count = 4
fake_total_size = total_size / chunck_count   

for i in range(0, chunck_count):
        print "request: ", i
        chunk = my_file.read(chunk_size)
        # conn.putrequest("POST", path) -- also causes the error
        conn.send(chunk)

      response = conn.getresponse()
      print response.read()

回复

request:  0
request:  1
request:  2  # --> might not even exist sometimes
Unexpected error: [Errno 32] Broken pipe

【问题讨论】:

    标签: python python-2.7 python-3.x https


    【解决方案1】:

    连接已关闭,因为您调用了conn.getresponse() 并且服务器关闭了它。除了传递 Connection: keep-alive 标头并希望服务器能够遵守之外,您在连接方面无能为力。

    如果要发送另一个 HTTP 请求,则必须以 conn.putrequest("POST", path) 或类似名称开头。

    【讨论】:

    • @Mataba:HTTP 不能那样工作。只有在您发送请求后才会收到回复。
    • 我发送了一个请求,我读了一个响应。现在我需要发送另一个请求而不重新创建连接并再次读取它。怎么样?
    • 即使我注释了第一个“response = conn.getresponse()”和“print response.read()”,它也会抛出同样的错误。
    • @Mataba:您的服务器支持哪些版本的 HTTP? getresponse() 仅在服务器支持时才保持连接打开。您可能还想传递一个 keep-alive 标头。
    • @Mataba:这是您的实际代码吗?您不能像这样以块的形式发送文件。将文件句柄传递给.send(),Python 会自动对其进行分块。
    猜你喜欢
    • 2017-01-25
    • 2021-12-29
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多