2011-07-14 120 views
19

我想通過向服務器發送自定義事件來獲取Python客戶端與使用Socket.io 0.7的Node.js服務器通信。格式化從python客戶端發送到socket.io node.js服務器的消息

基於我在GitHub和以下的WebSocket Python library上找到的Socket.io引用。

這裏是我到目前爲止的代碼:

節點服務器

io.sockets.on('connection', function (socket) { 
    socket.on('newimg', function(data) { 
     console.log(data); 
    }); 
}); 

Python客戶端

def handshake(host, port): 
    u = urlopen("http://%s:%d/socket.io/1/" % (host, port)) 
    if u.getcode() == 200: 
     response = u.readline() 
     (sid, hbtimeout, ctimeout, supported) = response.split(":") 
     supportedlist = supported.split(",") 
     if "websocket" in supportedlist: 
      return (sid, hbtimeout, ctimeout) 
     else: 
      raise TransportException() 
    else: 
     raise InvalidResponseException() 


try: 
    (sid, hbtimeout, ctimeout) = handshake(HOSTNAME, PORT) #handshaking according to socket.io spec. 
Except Exception as e: 
    print e 
    sys.exit(1) 
ws = websocket.create_connection("ws://%s:%d/socket.io/1/websocket/%s" % (HOSTNAME, PORT, sid)) 
print ws.recv() 
ws.send("2::") 
ws.send("5:1::{'name':'newimg', 'args':'bla'}") 
print ws.recv() 
print "Closing connection" 
ws.close() 

節點控制檯輸出

debug - client authorized 
info - handshake authorized 12738935571241622933 
debug - setting request GET /socket.io/1/websocket/12738935571241622933 
debug - set heartbeat interval for client 12738935571241622933 
debug - client authorized for 
debug - websocket writing 1:: 
debug - websocket received data packet 2:: 
debug - got heartbeat packet 
debug - websocket received data packet 5:1::{'name':'newimg', 'args':'bla'} 
debug - acknowledging packet automatically 
debug - websocket writing 6:::1 
info - transport end 
debug - set close timeout for client 12738935571241622933 
debug - cleared close timeout for client 12738935571241622933 
debug - cleared heartbeat interval for client 12738935571241622933 
debug - discarding transport 

Python的控制檯輸出

Done 
1:: 
6:::1 
Closing connection 

現在看來沒有被觸發插座事件,儘管服務器的ACK響應。所以消息被正確接收,但我假設,沒有正確格式化socket.io來觸發事件。

我沒想到框架是必要的,但是Archie1986似乎不同意他對此的迴應:Socket.IO Client Library in Python

什麼可能我做錯了嗎?

+1

已解決。只要我被允許,我會盡快接受我自己的答案。問題在於對JSON使用單引號而不是雙引號。 – rod

回答

14

已解決。我需要使用雙引號。單引號不是有效的JSON。 Woops。

ws.send("5:1::{'name':'newimg', 'args':'bla'}") 

變爲:

ws.send('5:1::{"name":"newimg", "args":"bla"}') 
20

我包rod的研成barebones socket.io client library

pip install -U socketIO-client 
python 
    from socketIO_client import SocketIO 
    with SocketIO('localhost', 8000) as socketIO: 
     socketIO.emit('aaa') 
     socketIO.wait(seconds=1) 
+0

socketIO.wait有什麼作用? 是秒= 1超時? – lmc

相關問題