websocket programming in python

1、websocket-server

https://github.com/google/pywebsocket

git clone https://github.com/google/pywebsocket.git

python setup.py install

python ./mod_pywebsocket/standalone.py -p 9998 -w ./example/

 

2、websocket-client

https://pypi.org/project/websocket_client/

import websocket
import threading
from threading import Thread
import time
import sys

def timer_cb():
      print("### timer_cb ###")
    global timer
    timer = threading.Timer(1,timer_cb)
    timer.start()

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):
            # send the message, then wait
            # so thread doesn't exit and socket
            # isn't closed
            ws.send("Hello %d" % i)
            time.sleep(1)

        time.sleep(1)
        ws.close()
        print("Thread terminating...")
        """
        timer = threading.Timer(1,timer_cb)
        timer.start()

    Thread(target=run).start()


if __name__ == "__main__":
    websocket.enableTrace(False)
    if len(sys.argv) < 2:
        host = "ws://localhost:9998/echo"
    else:
        host = sys.argv[1]
    ws = websocket.WebSocketApp(host,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

python echoapp_client.py

 

3、html的客户端,用作测试非常方便

pywebsocket-master\example/console.html

ws://localhost:9998/echo

ws://127.0.0.1:9998/echo

 

4、应用,移植

1) 因为需要用到3des + base64 + md5 加密,所以需要安装pycrypto库,

pycrypto库是个c和python复合型的库,需要编译,编译需要python-dev,所以系统必须要先安装python-dev

sudo apt-get install python-dev


2) 安装python虚拟机
sudo apt-get install python-pip
sudo pip install virtualenv

在python虚拟机里安装应用程序库
pip install websocket-client
pip install pycrypto

 

3) 可以启动应用程序了

virtualenv -p /usr/bin/python env
source env/bin/activate

(env) dong@ubuntu:~/sip_ws$ python sip_ws.py
 z1
{clientType":1,"userPrivileges":null,"isDeviceLogin":false,"isNeedSelectUser":false,"userRoleType":3,"isDoSuf":true,"failedInfo":"登录成功!","protocolHead":"gis_fl","protocolType":1000006}

 

5、websocke服务器t并发测试工具

https://github.com/chenmingle/test_websocket/blob/master/test_websocket.py

 

posted @ 2018-08-21 20:33  dong1  阅读(257)  评论(0编辑  收藏  举报