|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from urlparse import urlsplit |
| 3 | +import copy |
| 4 | + |
| 5 | +import gevent |
| 6 | +from gevent import Greenlet |
| 7 | +from gevent import socket |
| 8 | +from gevent.coros import Semaphore |
| 9 | +from gevent.queue import Queue |
| 10 | + |
| 11 | +from ws4py.client.threadedclient import WebSocketClient as ThreadedClient |
| 12 | +from ws4py.exc import HandshakeError, StreamClosed |
| 13 | + |
| 14 | +__all__ = ['WebSocketClient'] |
| 15 | + |
| 16 | +class WebSocketClient(ThreadedClient): |
| 17 | + def __init__(self, url, protocols=None, version='8'): |
| 18 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) |
| 19 | + ThreadedClient.__init__(self, url, protocols=protocols, version=version, sock=sock) |
| 20 | + |
| 21 | + self._lock = Semaphore() |
| 22 | + self._th = Greenlet(self._receive) |
| 23 | + self._messages = Queue() |
| 24 | + |
| 25 | + self.extensions = [] |
| 26 | + |
| 27 | + def opened(self, protocols, extensions): |
| 28 | + self.protocols = protocols |
| 29 | + self.extensions = extensions |
| 30 | + |
| 31 | + def received_message(self, m): |
| 32 | + self._messages.put(copy.deepcopy(m)) |
| 33 | + |
| 34 | + def write_to_connection(self, bytes): |
| 35 | + if not self.client_terminated: |
| 36 | + return self.sock.sendall(bytes) |
| 37 | + |
| 38 | + def closed(self, code, reason=None): |
| 39 | + self._messages.put(StreamClosed(code, reason)) |
| 40 | + |
| 41 | + def receive(self, msg_obj=False): |
| 42 | + msg = self._messages.get() |
| 43 | + |
| 44 | + if isinstance(msg, StreamClosed): |
| 45 | + return None |
| 46 | + |
| 47 | + if msg_obj: |
| 48 | + return msg |
| 49 | + else: |
| 50 | + return msg.data |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + |
| 55 | + ws = WebSocketClient('http://localhost:9000/', protocols=['http-only', 'chat']) |
| 56 | + ws.connect() |
| 57 | + |
| 58 | + ws.send("Hello world") |
| 59 | + print ws.receive() |
| 60 | + |
| 61 | + ws.send("Hello world again") |
| 62 | + print ws.receive() |
| 63 | + |
| 64 | + def incoming(): |
| 65 | + while True: |
| 66 | + m = ws.receive() |
| 67 | + if m is not None: |
| 68 | + print m, len(str(m)) |
| 69 | + if len(str(m)) == 35: |
| 70 | + ws.close() |
| 71 | + break |
| 72 | + else: |
| 73 | + break |
| 74 | + print "Connection closed!" |
| 75 | + |
| 76 | + def outgoing(): |
| 77 | + for i in range(0, 40, 5): |
| 78 | + ws.send("*" * i) |
| 79 | + |
| 80 | + # We won't get this back |
| 81 | + ws.send("Foobar") |
| 82 | + |
| 83 | + greenlets = [ |
| 84 | + gevent.spawn(incoming), |
| 85 | + gevent.spawn(outgoing), |
| 86 | + ] |
| 87 | + gevent.joinall(greenlets) |
0 commit comments