|
本帖最后由 dk1993 于 2016-5-9 11:50 编辑
#-*-coding:utf-8-*-
from kivy.support import install_twisted_reactor
install_twisted_reactor()
from twisted.protocols import basic
from twisted.internet import protocol,reactor
import re,json
class HttpEchoProtocol(basic.LineReceiver):
def __init__(self):
self.lines=[]
self.gotRequest=False
def lineReceived(self,line):
self.lines.append(line)
if not line and not self.gotRequest:
self.sendResponse()
self.gotRequest=True
def sendResponse(self):
params = self.lines[0].split(" ")[1]
if params not in ["/","/?"]:
dict_params = dict()
if params == '/':
self.factory.app.handle_message(dict_params)
else:
match = re.compile(r'(\w+)=(\w+)')
nowparams = match.findall(params)
for key,value in nowparams:
dict_params[key] = value
self.factory.app.handle_message(dict_params)
responseBody= json.dumps(dict_params)
self.sendLine("HTTP/1.0 200 OK")
self.sendLine("Content-Type: application/json")
self.sendLine("Content-Length: %i"%len(responseBody))
self.sendLine("")
self.transport.write(responseBody)
class EchoFactory(protocol.ServerFactory):
protocol = HttpEchoProtocol
def __init__(self, app):
self.app = app
from kivy.app import App
from kivy.uix.label import Label
class TwistedServerApp(App):
def build(self):
self.label = Label(text="server started\n")
reactor.listenTCP(8005, EchoFactory(self))
return self.label
def handle_message(self, msg):
print msg
if __name__ == '__main__':
TwistedServerApp().run()
|
|