使用高速公路作為 Websocket 工廠
Autobahn 包可用於 Python Web 套接字伺服器工廠。
要安裝,通常只需使用 terminal 命令即可
(對於 Linux):
sudo pip install autobahn
(對於 Windows):
python -m pip install autobahn
然後,可以在 Python 指令碼中建立一個簡單的 echo 伺服器:
from autobahn.asyncio.websocket import WebSocketServerProtocol
class MyServerProtocol(WebSocketServerProtocol):
'''When creating server protocol, the
user defined class inheriting the
WebSocketServerProtocol needs to override
the onMessage, onConnect, et-c events for
user specified functionality, these events
define your server's protocol, in essence'''
def onMessage(self,payload,isBinary):
'''The onMessage routine is called
when the server receives a message.
It has the required arguments payload
and the bool isBinary. The payload is the
actual contents of the "message" and isBinary
is simply a flag to let the user know that
the payload contains binary data. I typically
elsewise assume that the payload is a string.
In this example, the payload is returned to sender verbatim.'''
self.sendMessage(payload,isBinary)
if__name__=='__main__':
try:
importasyncio
except ImportError:
'''Trollius = 0.3 was renamed'''
import trollius as asyncio
from autobahn.asyncio.websocketimportWebSocketServerFactory
factory=WebSocketServerFactory()
'''Initialize the websocket factory, and set the protocol to the
above defined protocol(the class that inherits from
autobahn.asyncio.websocket.WebSocketServerProtocol)'''
factory.protocol=MyServerProtocol
'''This above line can be thought of as "binding" the methods
onConnect, onMessage, et-c that were described in the MyServerProtocol class
to the server, setting the servers functionality, ie, protocol'''
loop=asyncio.get_event_loop()
coro=loop.create_server(factory,'127.0.0.1',9000)
server=loop.run_until_complete(coro)
'''Run the server in an infinite loop'''
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
在此示例中,正在埠 9000 上的 localhost(127.0.0.1)
上建立伺服器。這是偵聽 IP 和埠。這是重要的資訊,因為使用它,你可以從調變解調器識別計算機的 LAN 地址和埠,儘管你擁有計算機的任何路由器。然後,使用谷歌調查你的 WAN IP,你可以設計你的網站,以便在埠 9000(在此示例中)將 WebSocket 訊息傳送到你的 WAN IP。
重要的是你從你的調變解調器向前移動,這意味著如果你有菊花連結到調變解調器的路由器,進入調變解調器的配置設定,從調變解調器埠轉發到連線的路由器,等等,直到你的計算機的最終路由器連線到具有在調變解調器埠 9000(在該示例中)上接收的資訊被轉發給它。