这里是我当前的代码:如何使用来自套接字的数据实现webpush?
#!/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()
正如你所看到的,我想接收数据时与回声调用WebPUSH的方法。因为我从来没有真正实例化WebPUSH,所以看起来我可以很轻松地调用这个方法。我试图将其转换为使用多服务方法,但似乎没有工作,虽然我确信我做错了什么。
没有(只要我可以谷歌)任何很好的例子在multiservice扭曲或至少这样的一个。
任何帮助将不胜感激。
目前尚不清楚,对我来说,至少,什么你实际上是想在这里完成。看起来你有一个UDP协议,它连接到HTTP实现的一半,并且你对类和实例之间的区别有些困惑。我不明白'MultiService'与什么有关。你想制作一个长轮询的Web服务器吗? – Glyph