File: test_gevent.py

package info (click to toggle)
python-socketpool 0.5.3-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 192 kB
  • sloc: python: 629; makefile: 4
file content (57 lines) | stat: -rw-r--r-- 1,482 bytes parent folder | download | duplicates (5)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# -*- coding: utf-8 -
#
# This file is part of socketpool.
# See the NOTICE for more information.

import gevent
from gevent.server import StreamServer

from socketpool.pool import ConnectionPool
from socketpool.conn import TcpConnector

# this handler will be run for each incoming connection in a dedicated greenlet
def echo(sock, address):
    print ('New connection from %s:%s' % address)

    while True:
        data = sock.recv(1024)
        if not data:
            break
        sock.send(data)
        print ("echoed %r" % data)



if __name__ == '__main__':
    import time

    options = {'host': 'localhost', 'port': 6000}
    pool = ConnectionPool(factory=TcpConnector, backend="gevent")
    server = StreamServer(('localhost', 6000), echo)
    gevent.spawn(server.serve_forever)


    def runpool(data):
        with pool.connection(**options) as conn:
            print ("conn: pool size: %s" % pool.size)

            sent = conn.send(data)
            echo_data = conn.recv(1024)
            assert data == echo_data

    start = time.time()
    jobs = [gevent.spawn(runpool, "blahblah") for _ in xrange(50)]

    gevent.joinall(jobs)
    delay = time.time() - start

    print ("final pool size: %s" % pool.size)

    with pool.connection(**options) as conn:
        print ("conn: pool size: %s" % pool.size)

        sent = conn.send("hello")
        echo_data = conn.recv(1024)
        assert "hello" == echo_data

    print ("final pool size: %s" % pool.size)