iT邦幫忙

0

Twisted web server 的問題(已解決)

大家好
我剛學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()
饅頭 iT邦新手 4 級 ‧ 2017-03-15 09:50:16 檢舉
我看有些範例是用
twisted.protocols裡的basic.LineReceiver
https://twistedmatrix.com/documents/current/core/examples/
我照上面的chatserver.py
但是自己用不出chatclientQAQ
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
souda
iT邦好手 1 級 ‧ 2017-04-05 10:58:43
最佳解答

只要是透過web顯示並能GET/POST就是webservice功能了.
你可以嘗試寫個py搭配web server(依照個人所需),透過瀏覽器GET即可.
http://0.0.0.0:8000/xx/yy xx代表object yy代表methods .

我要發表回答

立即登入回答