2013-05-27 46 views
0

首先,請允許我表達我對Stack Overflow社區的感謝 - 雖然我之前沒有發佈過,但我發現過去我的問題有無數解決方案。我非常感謝社區投入的時間和精力,使其成爲每個人的優秀資源。Python問題:無法使用請求庫獲取xhr-polling數據

我試圖從使用Socket.IO與XHR輪詢數據一起使用的服務器中獲取數據。雖然我可以看似與Python腳本連接,但我無法正確接收數據。

我已經看過了在Fiddler中的傳出和傳入數據包:每5秒鐘,瀏覽器收到有用的信息(即'5 ::: {「name」:「pollData」,「args」:[「< .. '),但是Python腳本接收NOOP響應(' 8 ::')

的代碼有問題的一部分:

reply = requests.get(URL + "/socket.io/1/?t=" + str(long(time.time()*1000)), headers=headers) 

session_id = reply.text.split(':')[0] 

print "Session ID:", session_id 

reply = requests.post(URL + "/socket.io/1/xhr-polling/" + session_id + "?t=" +    
         str(long(time.time()*1000)), data=message, headers=headers) 

print "Successfully subscribed." 

for i in range(5): 
    sleep(5) 
    reply = requests.get(URL + "/socket.io/1/xhr-polling/" + session_id + "?t=" + 
         str(long(time.time()*1000)), headers=headers) 
    print reply.text 

我使用的WebSocket客戶端嘗試,但它正在生成此錯誤:WebSocketException:Handshake Status 200

SocketIO客戶端產生此錯誤:SocketIOError:無法建立連接

更重要的是比使用另一個庫來解決這個問題,我想明白爲什麼會發生這種情況。由腳本和Chrome產生的傳出數據包至少對外行來說基本相同 - 他們爲什麼產生這樣不同的結果?

(請隨時歡迎詢問任何問題或獲得更多信息。)

回答

0

萬一它有利於人的未來,大量的試驗和錯誤,我意識到,它需要一個更GET請求時,它可以發佈之前之後訂閱信息。下面的一些代碼可能是多餘的,但它似乎工作:

reply = requests.get(url + "?t=" + get_timecode(), stream=True) 
session_id = reply.text.split(':')[0] 
main = requests.Session() 

print "Session ID:", session_id 

reply = main.get(url + "xhr-polling/" + session_id + "?t=" + get_timecode(), 
       stream=True) 
reply = main.post(url + "xhr-polling/" + session_id + "?t=" + get_timecode(), 
        data=subscribe, stream=True) 

print "Successfully subscribed." 

while 1: 
    reply = main.get(url + "xhr-polling/" + session_id + "?t=" + get_timecode(), 
        stream=True) 

[請注意,這只是必要的,因爲服務器的WebSocket被打破,Socket.IO不得不退卻對XHR輪詢。此外,可能有更簡單的方法來做到這一點。]

+0

我想你得到session_id ='0'來獲得一個會話ID,你可以在隨後的請求中使用。或者它是'1'? – abourget

相關問題