Exemple #1
0
def select(r, w, e, t=None):
    """a select() wrapper that allows tuples to represent sockets"""

    x = r or w or e
    if not x:
        return [], [], []
    x = x[0]

    for i in range(len(x)):  # identify proper tuple index
        # print 'type check', i, type(x[i])
        if isinstance(x[i], socket.socket):
            break

    if r:
        ra = zip(*r)[i]
    else:
        ra = ()
    if w:
        wa = zip(*w)[i]
    else:
        wa = ()
    if e:
        ea = zip(*e)[i]
    else:
        ea = ()

    r2, w2, e2 = select_call(ra, wa, ea, t)
    return (filter(lambda a: a[i] in r2, r), filter(lambda a: a[i] in w2, w), filter(lambda a: a[i] in e2, e))
Exemple #2
0
def client(sock):
    tell(sock, "CHAT", "Welcome to the server!")
    buf = ""  # packet buffer
    bytes_remaining = 0
    greenlet.getcurrent().parent.switch(None)
    while 1:

        # Received a partial packet; return control to parent greenlet while we wait for the rest of it
        if bytes_remaining:
            print "SWITCH: if bytes_remaining"
            greenlet.getcurrent().parent.switch(None)

        # In between incoming packets
        else:
            # A packet was completed?
            if buf:
                # Pass message packet up to parent greenlet
                print "SWITCH: if buf"
                greenlet.getcurrent().parent.switch(buf[:4], buf[4:])
                buf = ""

        # A packet is beginning...
        if (not bytes_remaining) and (not buf):
            # When parent greenlet returns to us, we have a new data ready
            buf = sock.recv(1)
            # Check for disconnect
            if len(buf) == 0:
                raise socket.error(107, "apparent disconnection")
            bytes_remaining = ord(buf) + 5
            buf = ""
            # Check that there is no more data available before returning control
            print
            print "select_call()"
            r, w, e = select_call([sock], [], [], 0)
            print "select_call() returned"
            print
            if not r:
                print "SWITCH: if not r"
                greenlet.getcurrent().parent.switch(None)

        # Receive more data
        more = sock.recv(bytes_remaining)
        # Check for disconnect
        if not more:
            raise socket.error(107, "apparent disconnection (packet dropped)")
        # Pump message packet buffering
        buf += more
        bytes_remaining -= len(more)