|
| 1 | +import asyncio |
| 2 | +import datetime |
| 3 | +from random import choice |
| 4 | + |
| 5 | +from rx import Observable |
| 6 | +from rx.subjects import Subject |
| 7 | +from rx.concurrency import IOLoopScheduler |
| 8 | + |
| 9 | +from tornado.ioloop import IOLoop |
| 10 | +from tornado.websocket import websocket_connect |
| 11 | + |
| 12 | +class Client: |
| 13 | + def __init__(self, host='localhost', port='8888'): |
| 14 | + self._url = 'ws://{}:{}/exchange'.format(host, port) |
| 15 | + self.conn = None |
| 16 | + self.opened = Subject() |
| 17 | + self.messages = Subject() |
| 18 | + # self.messages.subscribe(lambda msg: print('received: {}'.format(msg))) |
| 19 | + |
| 20 | + def connect(self): |
| 21 | + def on_connect(conn): |
| 22 | + print('on_connect') |
| 23 | + self.conn = conn |
| 24 | + self.opened.on_next(conn) |
| 25 | + self.opened.on_completed() |
| 26 | + self.opened.dispose() |
| 27 | + |
| 28 | + def on_message_callback(message): |
| 29 | + # print('on_message_callback') |
| 30 | + self.messages.on_next(message) |
| 31 | + |
| 32 | + print('connect to server') |
| 33 | + future = websocket_connect( |
| 34 | + self._url, |
| 35 | + on_message_callback=on_message_callback, |
| 36 | + ) |
| 37 | + Observable.from_future(future).subscribe(on_connect) |
| 38 | + |
| 39 | + def write_message(self, message): |
| 40 | + self.conn.write_message(message) |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + scheduler = IOLoopScheduler(IOLoop.current()) |
| 44 | + |
| 45 | + def make_say_hello(client, client_id): |
| 46 | + def say_hello(): |
| 47 | + print('{} client #{} is sending orders'.format( |
| 48 | + datetime.datetime.now(), client_id)) |
| 49 | + symbols = ['ABC', 'DEF', 'GHI', 'A', 'GS', 'GO'] |
| 50 | + quantities = [90, 100, 110] |
| 51 | + prices = [1.20, 1.21, 1.22, 1.23, 1.24, 1.25] |
| 52 | + client.write_message( |
| 53 | + 'order,{},{},buy,{},{}'.format(client_id, choice(symbols), choice(quantities), choice(prices))) |
| 54 | + client.write_message( |
| 55 | + 'order,{},{},sell,{},{}'.format(client_id, choice(symbols), choice(quantities), choice(prices))) |
| 56 | + |
| 57 | + def schedule_say_hello(conn): |
| 58 | + sleep = 5000 |
| 59 | + Observable \ |
| 60 | + .interval(sleep, scheduler=scheduler) \ |
| 61 | + .subscribe(lambda value: say_hello()) |
| 62 | + return schedule_say_hello |
| 63 | + |
| 64 | + clients = [] |
| 65 | + for client_id in range(10): |
| 66 | + client = Client(port='9999') |
| 67 | + client.opened.subscribe(make_say_hello(client, client_id)) |
| 68 | + clients.append(client) |
| 69 | + |
| 70 | + for client in clients: |
| 71 | + client.connect() |
| 72 | + IOLoop.current().start() |
0 commit comments