File: echo_gevent_client.py

package info (click to toggle)
python-ws4py 0.4.2%2Bdfsg1-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 688 kB
  • sloc: python: 4,500; makefile: 140; javascript: 96
file content (41 lines) | stat: -rw-r--r-- 978 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8 -*-
from gevent import monkey; monkey.patch_all()

import gevent
from ws4py.client.geventclient import WebSocketClient

if __name__ == '__main__':
    ws = WebSocketClient('ws://127.0.0.1:9000/ws', protocols=['http-only', 'chat'])
    ws.connect()

    ws.send("Hello world")
    print((ws.receive(),))

    ws.send("Hello world again")
    print((ws.receive(),))

    def incoming():
        while True:
            m = ws.receive()
            if m is not None:
                m = str(m)
                print((m, len(m)))
                if len(m) == 35:
                    ws.close()
                    break
            else:
                break
        print(("Connection closed!",))

    def outgoing():
        for i in range(0, 40, 5):
            ws.send("*" * i)

        # We won't get this back
        ws.send("Foobar")

    greenlets = [
        gevent.spawn(incoming),
        gevent.spawn(outgoing),
    ]
    gevent.joinall(greenlets)