我正在学习如何使用 Twisted AMP。我正在开发一个程序,将数据从客户端发送到服务器并将数据插入 SQLite3 DB。然后服务器将结果发送回客户端,指示成功或错误(尝试和除外可能不是最好的方法,但它只是我解决主要问题时的临时解决方案)。为了做到这一点,我修改了一个示例,该示例最初进行了求和并返回了结果,因此我意识到这可能不是执行我想做的最有效的方法。特别是我正在尝试对多次插入进行一些计时(即多次将数据发送到服务器以进行多次插入)并且我已经包含了我编写的代码。
我已经尝试了几种方法来解决这个问题,包括将 ClientCreator 传递给 reactor.callWhenRunning() 但你不能通过延迟来做到这一点。
任何有关如何执行此操作的建议、建议或帮助将不胜感激。这是代码。
服务器:
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
import sqlite3, time
class Insert(amp.Command):
arguments = [('data', amp.Integer())]
response = [('insert_result', amp.Integer())]
class Protocol(amp.AMP):
def __init__(self):
self.conn = sqlite3.connect('biomed1.db')
self.c =self.conn.cursor()
self.res=None
@Insert.responder
def dbInsert(self, data):
self.InsertDB(data) #call the DB inserter
result=self.res # send back the result of the insertion
return {'insert_result': result}
def InsertDB(self,data):
tm=time.time()
print "insert time:",tm
chx=data
PID=2
device_ID=5
try:
self.c.execute("INSERT INTO btdata4(co2_data, patient_Id, sensor_Id) VALUES ('%s','%s','%s')" % (chx, PID, device_ID))
except Exception, err:
print err
self.res=0
else:
self.res=1
self.conn.commit()
pf = Factory()
pf.protocol = Protocol
reactor.listenTCP(1234, pf)
reactor.run()
客户:
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
import time
class Insert(amp.Command):
arguments = [('data', amp.Integer())]
response = [('insert_result', amp.Integer())]
def connected(protocol):
return protocol.callRemote(Insert, data=5555).addCallback(gotResult)
def gotResult(result):
print 'insert_result:', result['insert_result']
tm=time.time()
print "stop", tm
def error(reason):
print "error", reason
tm=time.time()
print "start",tm
for i in range (10): #send data over ten times
ClientCreator(reactor, amp.AMP).connectTCP(
'127.0.0.1', 1234).addCallback(connected).addErrback(error)
reactor.run()
代码结束。
谢谢你。