2015年1月15日 星期四

[Python] 用Python 做 WebSocket Client

程式碼都來自網路上的範例,資料來源如下:

https://pypi.python.org/pypi/websocket-client/0.7.0

http://blog.liris.org/2011/01/pythonwebsocket.html


以下二個程式碼都經過測試可用,如果使用pip 出現

bash: pip: command not found


請參考這一篇可解




1.安裝 websocket-client

sudo pip install websocket-client

2.寫以下程式


import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:5000/chat",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open
    
    ws.run_forever()



會得到以下輸出

Sending 'Hello, World'...
Sent
Reeiving...
Received 'Hello, World'

3. 或是你可以寫成以下javascripti-like 風格 ,這個程式值得學習,

   會印出詳細的head內容。

import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:5000/chat",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open
    
    ws.run_forever()


輸出會是

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.org
Origin: http://echo.websocket.org
Sec-WebSocket-Key: 9QLjYJ8TT9qA+9/nJMRuOQ==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101 Web Socket Protocol Handshake
Connection: Upgrade
Date: Sat, 10 Jan 2015 04:40:23 GMT
Sec-WebSocket-Accept: dd1ebjFbrPUd0jg9XP/v0MYaSUE=
Server: Kaazing Gateway
Upgrade: websocket
-----------------------
send: '\x81\x872\xech2z\x89\x04^]\xccX'
Hello 0
send: '\x81\x87\x86\xe2\xc6\x94\xce\x87\xaa\xf8\xe9\xc2\xf7'
Hello 1
send: '\x81\x87\x99aD\xd2\xd1\x04(\xbe\xf6Av'
Hello 2
send: '\x88\x82\x85\xa6\x00\xcc\x86N'
thread terminating...

### closed ###


沒有留言:

張貼留言