python实现websocket的客户端压力测试

yipeiwu_com6年前Python基础

使用python进行websocket的客户端压力测试,这个代码是从github上 找到。然后简单修改了下。大神运用了进程池,以及线程池的内容。所以保存下来,学习学习

然后需要说明的是:本次用的python2.7,也尝试用python3.6,但是老实出现websocket-client包和python3不能兼容的情况,提示没有相关的方法。所以不得已最后又采用了python2

# -*- coding:utf-8 -*-
# __author__ == 'chenmingle'
 
import websocket
import time
import threading
import json
import multiprocessing
import uuid
from threadpool import ThreadPool, makeRequests
 
# 修改成自己的websocket地址
WS_URL = "xxxx"
# 定义进程数
processes = 4
# 定义线程数(每个文件可能限制1024个,可以修改fs.file等参数)
thread_num = 700
index = 1
 
 
def on_message(ws, message):
  # print(message)
  pass
 
 
def on_error(ws, error):
  print(error)
  pass
 
 
def on_close(ws):
  # print("### closed ###")
  pass
 
 
def on_open(ws):
  global index
  index = index + 1
 
  def send_thread():
    # 设置你websocket的内容
    # 每隔10秒发送一下数据使链接不中断
    while True:
      ws.send(u'hello服务器')
      time.sleep(10)
 
  t = threading.Thread(target=send_thread)
  t.start()
 
 
def on_start(num):
  time.sleep(5)
  # websocket.enableTrace(True)
  ws = websocket.WebSocketApp(WS_URL + str(num),
                on_message=on_message,
                on_error=on_error,
                on_close=on_close)
  ws.on_open = on_open
  ws.run_forever()
 
 
def thread_web_socket():
  # 线程池
  pool_list = ThreadPool(thread_num)
  num = list()
  # 设置开启线程的数量
  for ir in range(thread_num):
    num.append(ir)
  requests = makeRequests(on_start, num)
  [pool_list.putRequest(req) for req in requests]
  pool_list.wait()
 
 
if __name__ == "__main__":
  # 进程池
  pool = multiprocessing.Pool(processes=processes)
  # 设置开启进程的数量
  for i in xrange(processes):
    pool.apply_async(thread_web_socket)
  pool.close()
  pool.join()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现获取某天是某个月中的第几周

找了半天竟然没找到,如何在Python的datetime处理上,获取某年某月某日,是属于这个月的第几周。 无奈之下求助同学,同学给写了一个模块。【如果你知道Python有这个原生的库,请...

Django 创建/删除用户的示例代码

Django 创建/删除用户的示例代码

示意图: html: {# 用户管理 #} <div id="userManageDiv" style="display: none;"> <div...

Django中几种重定向方法

这里使用的是django1.5 需求: 有一个界面A,其中有一个form B, 前台提交B之后,后台保存数据之后,返回界面A,如果保存失败需要在A界面提示错误。 这里就需要后台的重定向,...

深入解析Python中的lambda表达式的用法

普通的数学运算用这个纯抽象的符号演算来定义,计算结果只能在脑子里存在。所以写了点代码,来验证文章中介绍的演算规则。 我们来验证文章里介绍的自然数及自然数运算规则。说到自然数,今天还百度了...

python使用nntp读取新闻组内容的方法

本文实例讲述了python使用nntp读取新闻组内容的方法。分享给大家供大家参考。具体实现方法如下: from nntplib import * s = NNTP('web.aioe...