File: test_eventlet.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 (79 lines) | stat: -rw-r--r-- 1,996 bytes parent folder | download | duplicates (6)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -
#
# This file is part of socketpool.
# See the NOTICE for more information.

import eventlet

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


# this handler will be run for each incoming connection in a dedicated greenlet

class EchoServer(object):

    def __init__(self, host, port):
        self.host = host
        self.port = port

        self.spool = eventlet.GreenPool()
        self.running = False
        self.server = None

    def start(self):
        eventlet.spawn(self.run)

    def run(self):
        self.server = eventlet.listen((self.host, self.port))
        self.running = True
        while self.running:
            try:
                sock, address = self.server.accept()
                print "accepted", address
                self.spool.spawn_n(self.handle, sock, address)
            except (SystemExit, KeyboardInterrupt):
                break


    def handle(self, 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)


    def stop(self):
        self.running = False


if __name__ == '__main__':
    import time

    options = {'host': 'localhost', 'port': 6000}
    pool = ConnectionPool(factory=TcpConnector, options=options,
            backend="eventlet")
    server = EchoServer('localhost', 6000)
    server.start()

    epool = eventlet.GreenPool()
    def runpool(data):
        print 'ok'
        with pool.connection() as conn:
            print 'sending'
            sent = conn.send(data)
            print 'send %d bytes' % sent
            echo_data = conn.recv(1024)
            print "got %s" % data
            assert data == echo_data

    start = time.time()
    _ = [epool.spawn(runpool, "blahblah") for _ in xrange(20)]

    epool.waitall()
    server.stop()
    delay = time.time() - start