编程语言
首页 > 编程语言> > python-websocket和socket.io命名空间

python-websocket和socket.io命名空间

作者:互联网

我会用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()

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

谢谢

解决方法:

您可以使用MIT许可下的PyPI上提供的socketIO-client.它支持单个套接字的不同名称空间.

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()

标签:websocket,socket-io,python
来源: https://codeday.me/bug/20191201/2078878.html