【发布时间】:2011-10-03 22:20:49
【问题描述】:
这是我当前的代码:
#!/usr/bin/env python
from twisted.application import internet, service
from twisted.application.service import IServiceMaker, MultiService
from twisted.protocols import basic
from twisted.internet import reactor, protocol, defer
from twisted.internet.protocol import DatagramProtocol
import datetime
class WebPUSH(basic.LineReceiver):
logTemplate = '''
<script type="text/javascript">
pushHandler.addLi('%s')
</script>
'''
def __init__(self):
self.gotRequest = False
def lineReceived(self, line):
if not self.gotRequest:
self.startResponse()
self.gotRequest = True
def startResponse(self):
self.sendLine('HTTP/1.1 200 OK')
self.sendLine('Content-Type: text/html; charset=utf-8')
self.sendLine('')
f = open('index.html', 'r')
self.transport.write( ''.join(f.read()) )
f.close()
self.logTime()
def logTime(self):
self.sendLine( self.logTemplate % datetime.datetime.now() )
#reactor.callLater(2, self.logTime)
class Echo(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
WebPUSH.logTime()
print "received %r from %s:%d" % (data, host, port)
self.transport.write(data, (host, port))
if __name__ == '__main__':
f = protocol.ServerFactory()
f.protocol = WebPUSH
reactor.listenTCP(8080, f)
reactor.listenUDP(9999, Echo())
reactor.run()
如您所见,当收到数据时,我试图从 Echo 调用 WebPUSH 中的方法。因为我从来没有真正实例化 WebPUSH,所以看起来我不能轻易地调用这个方法。我尝试将其转换为使用多服务方法,但这似乎不起作用,尽管我确信我做错了什么。
没有(据我所知)任何关于多服务的好例子,比如这样的扭曲或至少一个。
任何帮助将不胜感激。
【问题讨论】:
-
至少对我来说还不清楚你在这里实际想要完成什么。看起来您有一个 UDP 协议,它有点连接到 HTTP 实现的一半,并且您对类和实例之间的区别有点困惑。我不明白
MultiService与任何事情有什么关系。您是否正在尝试制作一个长轮询 Web 服务器?
标签: python http sockets streaming twisted