使用高速公路作为 Websocket 工厂

Autobahn 包可用于 Python Web 套接字服务器工厂。

Python Autobahn 包文档

要安装,通常只需使用 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(在该示例中)上接收的信息被转发给它。