大家好
我剛學python twisted
原本用twisted寫好可以再host 和 VM 互相連接
但是因為工作需求變了需要用到webserver(一樣用twisted的)(用http)
client主要就是呼叫server然後server可以回傳訊息給client(server可以一直開著等client叫)
1.應該要怎麼修改原本的程式碼變成webserver?(一樣是互相傳送訊息的)
底下是我原本的程式碼
client.py ↓↓↓
from twisted.internet import protocol, reactor
class KnockClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("Hey, H!")
def dataReceived(self, data):
if data.startswith("Hi, please wait..."):
print ("H:",data)
self.transport.loseConnection()
reactor.stop()
else:
print ("H:",data)
self.transport.loseConnection()
reactor.stop()
class KnockFactory(protocol.ClientFactory):
protocol = KnockClient
def main():
f = KnockFactory()
reactor.connectTCP("0.0.0.0", 5000, f)
reactor.run()
if __name__ == '__main__':
main()
server.py ↓↓↓
from twisted.internet import protocol, reactor
import os
class Knock(protocol.Protocol):
def dataReceived(self, data):
print 'Client:', data
if data.startswith("Hey, H!"):
response = "Hi, please wait..."
self.transport.write(response)
else:
response = "I don't know who you are!"
self.transport.write(response)
class KnockFactory(protocol.Factory):
def buildProtocol(self, addr):
return Knock()
reactor.listenTCP(5000, KnockFactory())
reactor.run()
只要是透過web顯示並能GET/POST就是webservice功能了.
你可以嘗試寫個py搭配web server(依照個人所需),透過瀏覽器GET即可.
http://0.0.0.0:8000/xx/yy xx代表object yy代表methods .