Websocket的长连接测试

import websocket
try:
    import thread
except ImportError:
    import _thread as thread
import time

# 服务器推送消息时,message可以接收,然后进行下一步操作
def on_message(ws, message):
    print(message)

# 程序报错时,会触发on_error事件
def on_error(ws, error):
    print(error)

# 主动断开连接时,会调用该函数
def on_close(ws):
    print("### closed ###")

# 连接建立后,会调用on_open函数
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-client库,不然这里会出错
    websocket.enableTrace(True)
   #建立连接 ws
= websocket.WebSocketApp("wss://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()

该代码为测试代码,可以根据自己项目的需求进行对应的修改

总结:

1.需要安装websocket-client库

2.如果是wss,跳过ssl的验证方法

ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

3.最好不要用强制杀线程的方式断开连接,这样有可能导致资源释放不完全,连接不能正常断开

可以通过输入特定的字符,或者检测目录下是否有特定文件,比如exit.txt等方式主动断开连接

也可以通过Timer设置固定多少时间后,主动断开连接

4.可以通过多线程的方式,启动多个线程,来测试多少个长连接可以同时在线。服务器广播时,能否正常接收消息

5.单机连接数量有限,可以通过多台测试机一起跑,来达到目标连接数

6.ws.run_forever(ping_interval=60,ping_timeout=5) 

ping_interval:自动发送“ping”命令,每个指定的时间(秒),如果设置为0,则不会自动发送。

ping_timeout:如果没有收到pong消息,则为超时(秒)。

posted @ 2020-11-10 10:22  RonyJay  阅读(2541)  评论(0编辑  收藏  举报