【问题标题】:python-websocket and socket.io namespacepython-websocket 和 socket.io 命名空间
【发布时间】:2012-06-19 09:50:18
【问题描述】:

我会用 python 编写一个 websocket 客户端来连接到一个用 socket.io 编写的服务器。 我当前的代码,取自1,如下:

import websocket, httplib, sys, asyncore
def connect(server, port):

    print("connecting to: %s:%d" %(server, port))

    conn  = httplib.HTTPConnection(server + ":" + str(port))
    conn.request('POST','/socket.io/1/')
    resp  = conn.getresponse() 
    hskey = resp.read().split(':')[0]
    ws = websocket.WebSocket(
                'ws://'+server+':'+str(port)+'/socket.io/1/websocket/'+hskey,
                onopen   = _onopen,
                onmessage = _onmessage,
                onclose = _onclose)

    return ws

def _onopen():
    print("opened!")

def _onmessage(msg):
    print("msg: " + str(msg))

def _onclose():
    print("closed!")


if __name__ == '__main__':

    server = 'localhost'
    port = 8081

    ws = connect(server, port)

    try:
        asyncore.loop()
    except KeyboardInterrupt:
        ws.close()

我的问题是如何连接到特定的命名空间?

谢谢

【问题讨论】:

    标签: python websocket socket.io


    【解决方案1】:

    您可以使用socketIO-client,它在 PyPI 上根据 MIT 许可提供。它支持单个套接字的不同命名空间。

    from socketIO_client import SocketIO, BaseNamespace
    
    class MainNamespace(BaseNamespace):
    
        def on_aaa(self, *args):
            print 'aaa', args
    
    class ChatNamespace(BaseNamespace):
    
        def on_bbb(self, *args):
            print 'bbb', args
    
    class NewsNamespace(BaseNamespace):
    
        def on_ccc(self, *args):
            print 'ccc', args
    
    mainSocket = SocketIO('localhost', 8000, MainNamespace)
    chatSocket = mainSocket.connect('/chat', ChatNamespace)
    newsSocket = mainSocket.connect('/news', NewsNamespace)
    mainSocket.wait()
    

    【讨论】:

    【解决方案2】:

    您可以更轻松地更改命名空间。

    from socketIO_client import SocketIO, BaseNamespace
    socket = SocketIO('192.168.4.47', 7777)
    chat = socket.define(BaseNamespace, '/openchat')
    chat.emit('echo', 'hello openchat my name is Anderson')
    

    我已经在https://pypi.python.org/pypi/socketIO-client解决了这个问题

    希望你能节省很多时间

    【讨论】:

      【解决方案3】:

      我建议您使用 Wireshark 嗅探与 Socket.IO 建立的连接,并通过您的 websocket 连接发送正确的数据包到假冒 Socket.IO 客户端.. 然后实现数据包和消息协议Socket.IO 层。

      这里有数据包类型的基本文档:

      http://gevent-socketio.readthedocs.org/en/latest/packet.html#module-socketio.packet

      此外,您可以阅读显示线级协议(您可能需要实现)的测试套件:

      https://github.com/abourget/gevent-socketio/blob/master/tests/test_packet.py

      您将在文档中看到,在不同类型的数据包中指定了特定的命名空间。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-11
        • 2012-10-20
        • 2018-06-10
        • 1970-01-01
        • 2012-11-10
        • 2021-02-27
        • 1970-01-01
        • 2014-12-11
        相关资源
        最近更新 更多