无法在单个连接中发送多个请求数据 - 套接字错误

时间:2013-08-13 05:12:17

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

这个问题来自我以前的问题。我需要一次向服务器多次次(在此特定示例中为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()

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

请注意,错误不是因为服务器确实失败,而是因为套接字,但为什么?

如何摆脱错误?

更新

同样的错误:

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

UPDATE2:

仍然没有运气:

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

1 个答案:

答案 0 :(得分:2)

连接已关闭,因为您调用了conn.getresponse()并且服务器已将其关闭。除了传递Connection: keep-alive标题之外,您可以从连接方面对此做些什么,并希望服务器符合要求。

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