2014-10-29 58 views
0

我正在嘗試爲類實現一個簡單的epoll web服務器。一切工作很好,直到我嘗試發送一個大文件。我注意到它發送了大約2/3的數據,然後只是坐在那裏,什麼都不做。這是我如何確保我所有的數據被髮送:無法發送大文件Python

def sendResponse(self,fd,response): 
    if response: 
     totalsent = 0 
     MSGLEN = len(response) 
     while totalsent < MSGLEN: 
      sent = self.clients[fd].send(response[totalsent:]) 
      if sent == 0: 
       raise RuntimeError("socket connection broken") 
      totalsent = totalsent + sent 
    else: 
     self.poller.unregister(fd) 
     self.clients[fd].close() 
     del self.clients[fd] 

我是否提到過這個作品在中小型文件。我只在發送1.7 Mbs或更大的文件時才注意到它中斷。

+0

如果您的代碼停止發送並掛起,則發送緩衝區可能已滿。客戶端是否正確讀取了所有發送的數據?你的發送循環看起來很好。 – 2014-10-29 05:45:07

回答

0

如果可以,跳過重新發明輪子&的階段使用ZeroMQ消息傳遞層。

這樣,您的代碼可能會忘記所有低槓桿問題,而您的開發時間&專注於您的問題域問題。 ZeroMQ提供了一個概念和一套現成的工具,用於添加(幾乎)線性可伸縮性,資源池,故障恢復能力,更高層的抽象協議等等。

對於初始的一塊蛋糕,從Nicholas Piel

品味美景的一週支出與皮特斯Hintjens書「代碼連接,第1卷」將向您介紹分佈式處理的一個新的世界,你必須準備好在您的指尖,只是準備重新使用大師的專業知識。

你會得到什麼?

魔鬼般的速度快,是它從一個代碼簡單的像這樣的幾個字節或幾個GB的BLOB,低延遲和等等,所有這些:

def sendResponse(self, aZmqConnectionToCounterparty, response): 
    if response: 
      try: 
       aZmqConnectionToCounterparty.send(response, zmq.NOBLOCK) 
      except ZMQerror: 
       ''' handle ZMQerror ''' 
      except ValueError: 
       ''' handle ValueError ''' 
      except TypeError: 
       ''' handle TypeError ''' 
    ... 

PyZMQ文件上寫着:

.send(data, flags = 0, copy = True, track = False) 
Send a message on this socket. 

This queues the message to be sent by the IO thread at a later time. 

Parameters: 
----------- 
data: object, str, Frame The content of the message. 
flags: int     Any supported flag: NOBLOCK, SNDMORE. 
copy: bool     Should the message be sent in a copying or non-copying manner. 
track: bool     Should the message be tracked for notification 
           that ZMQ has finished with it? (ignored if copy = True) 

Returns: 
-------- 
None: if copy or not track 

None if message was sent, raises an exception otherwise. 

MessageTracker: if track and not copy 

a MessageTracker object, whose pending property will be True until the send is completed. 

Raises: 
------- 
TypeError     If a unicode object is passed 
ValueError     If track=True, but an untracked Frame is passed. 
ZMQError      If the send does not succeed for any reason.