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



这个问题来自我以前的问题。我需要一次将一些数据发送到服务器多次(在本例中为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()

更新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

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

如果你想发送另一个HTTP请求,你必须从conn.putrequest("POST", path)或类似的东西开始。

最新更新