Skip to content

Instantly share code, notes, and snippets.

@mrjoes
Created December 11, 2011 21:00
Show Gist options
  • Save mrjoes/1462715 to your computer and use it in GitHub Desktop.
Save mrjoes/1462715 to your computer and use it in GitHub Desktop.
Dummy websocket client
import websocket
import threading
import random
import time
import sys
class Worker(threading.Thread):
def __init__(self, *args, **kwargs):
self.lock = threading.RLock()
self.packets_sent = 0
self.packets_recv = 0
self.need_work = True
super(Worker, self).__init__(*args, **kwargs)
def dump(self):
with self.lock:
result = (self.packets_sent, self.packets_recv)
self.packets_sent = 0
self.packets_recv = 0
return result
def run(self):
id = str(random.randint(0,100000))
ws = websocket.create_connection('ws://localhost:8080')
while self.need_work:
ws.send(id)
with self.lock:
self.packets_sent += 1
msg = ws.recv()
with self.lock:
self.packets_recv += 1
while msg != id:
msg = ws.recv()
with self.lock:
self.packets_recv += 1
if __name__ == '__main__':
random.seed(time.time())
num = 1
if len(sys.argv) > 1:
num = int(sys.argv[1])
# Create workers
workers = [Worker() for x in xrange(num)]
# Start workers
for w in workers:
w.start()
# Poll for statistics
try:
while True:
for w in workers:
data = w.dump()
print 'sent: %d, recv: %d' % data
print '------'
time.sleep(1)
except KeyboardInterrupt:
for w in workers:
w.need_work = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment