2012-06-19 57 views
3

我会在python中编写一个websocket客户端来连接到使用socket.io编写的服务器。 我当前的代码,从1采取如下:python-websocket和socket.io命名空间

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

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

感谢

回答

2

您可以使用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() 
+0

对于那些你,我相信该格式最近略有变化。如果您遇到困难,请阅读文档。 https://pypi.python.org/pypi/socketIO-client – simonmorley

0

我建议你使用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

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

希望这会有所帮助。

+0

我所期待的简单的东西,我还是谢谢你:使用该d – Emanuele

1

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

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

这个问题希望大家节省您的时间了很多