2014-10-29 48 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.