Ejemplo n.º 1
0
 def run(self):
     """Block and start listening for connections from clients. An
     interrupt (^C) closes the server.
     """
     self.startup_time = time.time()
     bluelet.run(bluelet.server(self.host, self.port,
                                Connection.handler(self)))
Ejemplo n.º 2
0
 def run(self):
     """Block and start listening for connections from clients. An
     interrupt (^C) closes the server.
     """
     self.startup_time = time.time()
     bluelet.run(bluelet.server(self.host, self.port,
                                Connection.handler(self)))
Ejemplo n.º 3
0
def run_bluelet():
    # No lock is required guarding the shared variable because only
    # one thread is actually running at a time.
    tweets = {}

    def fetch(username):
        url = URL % username
        data = yield AsyncHTTPClient.fetch(url)
        tweets[username] = json.loads(data)[0]['text']

    def crawl():
        for username in USERNAMES:
            yield bluelet.spawn(fetch(username))

    bluelet.run(crawl())
    return tweets
Ejemplo n.º 4
0
def run_bluelet():
    # No lock is required guarding the shared variable because only
    # one thread is actually running at a time.
    tweets = {}

    def fetch(username):
        url = URL % username
        data = yield AsyncHTTPClient.fetch(url)
        tweets[username] = json.loads(data)[0]['text']

    def crawl():
        for username in USERNAMES:
            yield bluelet.spawn(fetch(username))

    bluelet.run(crawl())
    return tweets
Ejemplo n.º 5
0
    def test_signal(self):
        def func1(sig):
            yield bluelet.sleep(3)
            yield sig.set()

        def func2(sig):
            yield sig.wait()

        def body():
            sig = bluelet.Signal()
            handle1 = func1(sig)
            handle2 = func2(sig)
            yield bluelet.spawn(handle1, daemon=False)
            yield bluelet.spawn(handle2, daemon=False)
            yield bluelet.join(handle2)

        bluelet.run(body())
Ejemplo n.º 6
0
    def test_sem(self):
        def func1(sem):
            yield bluelet.sleep(3)
            yield sem.release()

        def func2(sem):
            yield sem.acquire()

        def body():
            sem = bluelet.Semaphore(0)
            handle1 = func1(sem)
            handle2 = func2(sem)
            yield bluelet.spawn(handle1, daemon=False)
            yield bluelet.spawn(handle2, daemon=False)
            yield bluelet.join(handle2)

        bluelet.run(body())
Ejemplo n.º 7
0
    def test_cond(self):
        def func1(cond):
            yield bluelet.sleep(3)
            yield cond.acquire()
            yield cond.notify_all()
            yield cond.release()

        def func2(cond):
            yield cond.acquire()
            yield cond.wait()
            yield cond.release()

        def body():
            cond = bluelet.Condition()
            handle1 = func1(cond)
            handle2 = func2(cond)
            yield bluelet.spawn(handle1, daemon=False)
            yield bluelet.spawn(handle2, daemon=False)
            yield bluelet.join(handle2)

        bluelet.run(body())
Ejemplo n.º 8
0
    def test_wait_for(self):
        def func1(param):
            yield bluelet.sleep(param)
            yield bluelet.end(1)

        def interrupt_func(sig, param):
            yield bluelet.sleep(param)
            yield sig.set()

        def body():
            t = time.time()
            res, status = yield bluelet.wait_for(func1(100), timeout=1)
            assert res == False and status is None
            passed = time.time() - t
            assert passed > 1 and passed < 2

            t = time.time()

            # Spawn an interrupt task
            sig = bluelet.Signal()
            sig.clear()
            handle = interrupt_func(sig, 0.5)
            yield bluelet.spawn(handle, daemon=False)

            res, status = yield bluelet.wait_for(func1(1),
                                                 timeout=2,
                                                 interrupt=sig)
            assert res == False and status == None
            passed = time.time() - t
            assert passed > 0.5 and passed < 1
            yield bluelet.kill(handle)

            t = time.time()
            res, status = yield bluelet.wait_for(func1(0.5), timeout=1)
            assert res == True and status == 1
            passed = time.time() - t
            assert passed > 0.5 and passed < 1

        bluelet.run(body())
Ejemplo n.º 9
0
    def test_lock_autorelease(self):
        def func1(lock):
            yield lock.acquire()
            yield bluelet.sleep(100)
            yield lock.release()

        def func2(lock):
            yield bluelet.sleep(1)
            yield lock.acquire()
            yield bluelet.sleep(1)
            yield lock.release()

        def body():
            lock = bluelet.Lock()
            handle1 = func1(lock)
            handle2 = func2(lock)
            yield bluelet.spawn(handle1)
            yield bluelet.spawn(handle2)
            yield bluelet.sleep(1)
            yield bluelet.kill(handle1)
            yield bluelet.sleep(1)
            yield bluelet.join(handle2)

        bluelet.run(body())
Ejemplo n.º 10
0
 def run(self):
     # Receive on the socket in this thread.
     bluelet.run(self.main_coro())
Ejemplo n.º 11
0
 def run(self):
     amend_path()
     try:
         bluelet.run(self.communicate())
     except KeyboardInterrupt:
         pass
Ejemplo n.º 12
0
        if i!=conn:#Se i for diferente da minha conta
            yield i.sendall(mensagem.encode())#Envia para todos na lista contas menos para mim
    while True:
        data = yield conn.recv(1024)#pega dado da conexão
        if not data:
            break
        for n in nomes:#Pecorre a lista nomes
            comp="%s:exit()"%n#Irá servir como base para comparar
            if comp==data.decode('utf8'):#Se a mensagem em data for igual a "nome da pessoa: exit()" 
                nomes.remove(n)#Se remove o nome de quem enviou da lista nomes
                contas.remove(conn)#Remove o conn de quem enviou da lista contas
                resposta ="%s saiu da conversa" %n#Resposta que será enviada aos clientes conectados 
                data = resposta.encode()
        for n in nomes:
            commandWhoIsOn = "%s:Who is on?" %n
            if commandWhoIsOn==data.decode('utf8'):
                data=b''
                for userOn in nomes:
                    who ="%s está online" %userOn
                    yield conn.sendall(who.encode())
                    
        for i in contas:#Vai pegar todas as conexões que estão na lista contas
            if i!=conn:#Se "i" for diferente da conexão que está enviando a mensagem
                yield i.sendall(data)#envia a mensagem para as outra conexões
		
contas=[]
nomes=[]
if __name__=="__main__":
    print("Servidor Rodando...")
    bluelet.run(bluelet.server('', 4915, echoer))
Ejemplo n.º 13
0
import bluelet


def connecho():
    c = yield bluelet.connect("127.0.0.1", 8000)

    game_finish = False
    while ~game_finish:
        yield c.send("Ana are mere".encode())
        data = c.recv(1024)
        print("SERVER:", data)


def main():
    yield bluelet.spawn(connecho())


bluelet.run(main())
Ejemplo n.º 14
0
 def start_job(self, jobid, func, *args, **kwargs):
     # Synchronously send on the socket in the *calling* thread.
     with self.ready_condition:
         while not self.ready:
             self.ready_condition.wait()
     bluelet.run(self.send_job(jobid, func, *args, **kwargs))
Ejemplo n.º 15
0
def child():
    print 'Child started.'
    yield bluelet.null()
    print 'Child resumed.'
    yield bluelet.null()
    print 'Child ending.'
    yield bluelet.end(42)
def parent():
    print 'Parent started.'
    yield bluelet.null()
    print 'Parent resumed.'
    result = yield child()
    print 'Child returned:', repr(result)
    print 'Parent ending.'

def exc_child():
    yield bluelet.null()
    raise Exception()
def exc_parent():
    try:
        yield exc_child()
    except Exception, exc:
        print 'Parent caught:', repr(exc)
def exc_grandparent():
    yield bluelet.spawn(exc_parent())

if __name__ == '__main__':
    bluelet.run(parent())
    bluelet.run(exc_grandparent())
Ejemplo n.º 16
0
 def run(self):
     bluelet.run(self.coro)
Ejemplo n.º 17
0
    print 'Child returned:', repr(result)
    print 'Parent ending.'

def exc_child():
    yield bluelet.null()
    raise Exception()
def exc_parent():
    try:
        yield exc_child()
    except Exception, exc:
        print 'Parent caught:', repr(exc)
def exc_grandparent():
    yield bluelet.spawn(exc_parent())

if __name__ == '__main__':
    bluelet.run(parent())
    bluelet.run(exc_grandparent())

########NEW FILE########
__FILENAME__ = echo
from __future__ import print_function
import sys
sys.path.insert(0, '..')
import bluelet

def echoer(conn):
    print('Connected: %s' % conn.addr[0])
    try:
        while True:
            data = yield conn.recv(1024)
            if not data:
Ejemplo n.º 18
0
from __future__ import print_function
import sys
sys.path.insert(0, '..')
import bluelet


def sleeper(duration):
    print('Going to sleep for %i seconds...' % duration)
    yield bluelet.sleep(duration)
    print('...woke up after %i seconds.' % duration)


def sleepy():
    for i in (0, 1, 3, 5):
        yield bluelet.spawn(sleeper(i))


if __name__ == '__main__':
    bluelet.run(sleepy())
Ejemplo n.º 19
0
    # Get the HTTP request.
    request = []
    while True:
        line = (yield conn.readline(b'\r\n')).strip()
        if not line:
            # End of headers.
            break
        request.append(line)

    # Make sure a request was sent.
    if not request:
        return

    # Parse and log the request and get the response values.
    method, path, headers = parse_request(request)
    print('%s %s' % (method, path))
    status, headers, content = respond(method, path, headers)

    # Send response.
    yield conn.sendall(("HTTP/1.1 %s\r\n" % status).encode('utf8'))
    for key, value in headers.items():
        yield conn.sendall(("%s: %s\r\n" % (key, value)).encode('utf8'))
    yield conn.sendall(b"\r\n")
    yield conn.sendall(content)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        ROOT = os.path.expanduser(sys.argv[1])
    print('http://127.0.0.1:8000/')
    bluelet.run(bluelet.server('', 8000, webrequest))
Ejemplo n.º 20
0
 def run(self):
     bluelet.run(self.coro)
Ejemplo n.º 21
0
        connections[0] = yield listener.accept()  # Avoiding nonlocal.
    listen_thread = listen()
    yield bluelet.spawn(listen_thread)

    connections[1] = yield bluelet.connect('127.0.0.1', port)

    yield bluelet.join(listen_thread)

    # Wrap sockets in Endpoints.
    sentinel = uuid.uuid4().bytes  # Somewhat hacky...
    yield bluelet.end((Endpoint(connections[0], sentinel),
                       Endpoint(connections[1], sentinel)))

def main():
    ep1, ep2 = yield channel()
    if False:
        # Run in bluelet (i.e., no parallelism).
        yield bluelet.spawn(server(ep1))
        yield bluelet.spawn(client(ep2))
    else:
        # Run in separate processes.
        ta = BlueletProc(server(ep1))
        tb = BlueletProc(client(ep2))
        ta.start()
        tb.start()
        ta.join()
        tb.join()

if __name__ == '__main__':
    bluelet.run(main())
Ejemplo n.º 22
0
import bluelet


def echoer(conn):
    while True:
        data = yield conn.recv(1024)
        if not data:
            break
        print "CLIENT:", data
        yield conn.sendall(data)


bluelet.run(bluelet.server('127.0.0.1', 4915, echoer))
Ejemplo n.º 23
0
import sys
sys.path.insert(0, '..')
import bluelet


def echoer(conn):
    while True:
        data = yield conn.recv(1024)
        if not data:
            break
        yield conn.sendall(data)


if __name__ == '__main__':
    bluelet.run(bluelet.server('', 4915, echoer))
Ejemplo n.º 24
0
 def start_job(self, jobid, func, *args, **kwargs):
     # Synchronously send on the socket in the *calling* thread.
     with self.ready_condition:
         while not self.ready:
             self.ready_condition.wait()
     bluelet.run(self.send_job(jobid, func, *args, **kwargs))
Ejemplo n.º 25
0
sys.path.insert(0, '..')
import bluelet

def echoer(conn):
    print 'Connected: %s' % conn.addr[0]
    try:
        while True:
            data = yield conn.recv(1024)
            if not data:
                break
            print 'Read from %s: %s' % (conn.addr[0], repr(data))
            yield conn.sendall(data)
    finally:
        print 'Disconnected: %s' % conn.addr[0]
        conn.close()
        
def echoserver():
    listener = bluelet.Listener('', 4915)
    try:
        while True:
            conn = yield listener.accept()
            yield bluelet.spawn(echoer(conn))
    except KeyboardInterrupt:
        print
    finally:
        print 'Exiting.'
        listener.close()

if __name__ == '__main__':
    bluelet.run(echoserver())
Ejemplo n.º 26
0
 def bluelet(self):
     bluelet.run(self.app())
Ejemplo n.º 27
0
 def run(self):
     # Receive on the socket in this thread.
     bluelet.run(self.main_coro())
Ejemplo n.º 28
0
    request = []
    while True:
        line = (yield conn.readline(b'\r\n')).strip()
        if not line:
            # End of headers.
            break
        request.append(line)

    # Make sure a request was sent.
    if not request:
        return

    # Parse and log the request and get the response values.
    method, path, headers = parse_request(request)
    print('%s %s' % (method, path))
    status, headers, content = respond(method, path, headers)

    # Send response.
    yield conn.sendall(("HTTP/1.1 %s\r\n" % status).encode('utf8'))
    for key, value in headers.items():
        yield conn.sendall(("%s: %s\r\n" % (key, value)).encode('utf8'))
    yield conn.sendall(b"\r\n")
    yield conn.sendall(content)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        ROOT = os.path.expanduser(sys.argv[1])
    print('http://127.0.0.1:8000/')
    bluelet.run(bluelet.server('', 8000, webrequest))
Ejemplo n.º 29
0
from __future__ import print_function
import sys
sys.path.insert(0, '..')
import bluelet

def sleeper(duration):
    print('Going to sleep for %i seconds...' % duration)
    yield bluelet.sleep(duration)
    print('...woke up after %i seconds.' % duration)
        
def sleepy():
    for i in (0, 1, 3, 5):
        yield bluelet.spawn(sleeper(i))

if __name__ == '__main__':
    bluelet.run(sleepy())
if __name__ == '__main__':
    
    
    host = socket.gethostname()  # '127.0.0.1' can also be used
    serverfile = open('server.txt')
    lines = serverfile.readlines()
    #taskfile = open('test.txt')
    #tlines = taskfile.readlines()

    server_s = []
    task_types = []
    
    data1 = []
    
    bluelet.run(bluelet.server('', 9001, echoer))
    
    for line in lines:
        line = line.split(' ')
        for i in range (0,3):
            line[i] = int(line[i])
        if len(line) == 4:
            name = line[3]
        elif len(line) == 3:
            name = 'Server'
        else:
            raise Exception('Invalid Server.txt file structure')
        if int(line[0])>0:
            server_s.append(Server(capacity=line[0], occ=line[1], port=line[2], name=name))
    
    temp2 = []
Ejemplo n.º 31
0
if __name__ == '__main__':
    
    
    host = socket.gethostname()  # '127.0.0.1' can also be used
    serverfile = open('server.txt')
    lines = serverfile.readlines()
    #taskfile = open('test.txt')
    #tlines = taskfile.readlines()

    server_s = []
    task_types = []
    
    data1 = []
    
    bluelet.run(bluelet.server('', 9001, echoer))
    
    for line in lines:
        line = line.split(' ')
        for i in range (0,3):
            line[i] = int(line[i])
        if len(line) == 4:
            name = line[3]
        elif len(line) == 3:
            name = 'Server'
        else:
            raise Exception('Invalid Server.txt file structure')
        if int(line[0])>0:
            server_s.append(Server(capacity=line[0], occ=line[1], port=line[2], name=name))
    
    temp2 = []
Ejemplo n.º 32
0
 def run(self):
     amend_path()
     try:
         bluelet.run(self.communicate())
     except KeyboardInterrupt:
         pass
Ejemplo n.º 33
0
 def run(self):
     bluelet.run(bluelet.server('', cw.PORT, self.communicate))
Ejemplo n.º 34
0
def echoer(conn):
    print('Connected: %s' % conn.addr[0])
    try:
        while True:
            data = yield conn.recv(1024)
            if not data:
                break
            print('Read from %s: %s' % (conn.addr[0], repr(data)))
            yield conn.sendall(data)
    finally:
        print('Disconnected: %s' % conn.addr[0])
        conn.close()


def echoserver():
    listener = bluelet.Listener('', 4915)
    try:
        while True:
            conn = yield listener.accept()
            yield bluelet.spawn(echoer(conn))
    except KeyboardInterrupt:
        print()
    finally:
        print('Exiting.')
        listener.close()


if __name__ == '__main__':
    bluelet.run(echoserver())