您好,登錄后才能下訂單哦!
使用python進(jìn)行websocket的客戶端壓力測(cè)試,這個(gè)代碼是從github上 找到。然后簡單修改了下。大神運(yùn)用了進(jìn)程池,以及線程池的內(nèi)容。所以保存下來,學(xué)習(xí)學(xué)習(xí)
然后需要說明的是:本次用的python2.7,也嘗試用python3.6,但是老實(shí)出現(xiàn)websocket-client包和python3不能兼容的情況,提示沒有相關(guān)的方法。所以不得已最后又采用了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" # 定義進(jìn)程數(shù) processes = 4 # 定義線程數(shù)(每個(gè)文件可能限制1024個(gè),可以修改fs.file等參數(shù)) 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(): # 設(shè)置你websocket的內(nèi)容 # 每隔10秒發(fā)送一下數(shù)據(jù)使鏈接不中斷 while True: ws.send(u'hello服務(wù)器') 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() # 設(shè)置開啟線程的數(shù)量 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__": # 進(jìn)程池 pool = multiprocessing.Pool(processes=processes) # 設(shè)置開啟進(jìn)程的數(shù)量 for i in xrange(processes): pool.apply_async(thread_web_socket) pool.close() pool.join()
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。