示例#1
0
clients_lock = asyncio.Lock()


def chat(websocket):

    with (yield from clients_lock):
        clients.append(websocket)

    try:
        while True:
            frame = yield from websocket.recv()
            if frame is None:
                break

            client_copy = None
            with (yield from clients_lock):
                client_copy = list(clients)

            for client in client_copy:
                if client is websocket:
                    continue
                yield from client.send(frame)
    finally:
        with (yield from clients_lock):
            clients.remove(websocket)


server = asyncws.start_server(chat, "127.0.0.1", 8000)
asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()
示例#2
0
import asyncio
import asyncws

@asyncio.coroutine
def echo(websocket):
    while True:
        frame = yield from websocket.recv()
        if frame is None:
            break
        yield from websocket.send(frame)


loop = asyncio.get_event_loop()
server = loop.run_until_complete(
    asyncws.start_server(echo, '127.0.0.1', 8000))
try:
    loop.run_forever()
except KeyboardInterrupt as e:
    server.close()
    loop.run_until_complete(server.wait_closed())
finally:
    loop.close()
示例#3
0
    for client in client_copy:
        yield from client.send("Connected %s" % peer)

    try:
        while True:
            frame = yield from websocket.recv()
            if frame is None:
                break

            with (yield from clients_lock):
                client_copy = list(clients)

            text = "%s> %s" % (peer, str(frame))

            for client in client_copy:
                if client is websocket:
                    continue

                yield from client.send(text)
    finally:
        with (yield from clients_lock):
            clients.remove(websocket)
            client_copy = list(clients)

        for client in client_copy:
            yield from client.send("Disconnected %s" % peer)

server = asyncws.start_server(chat, '127.0.0.1', 8000)
asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()
示例#4
0
import asyncio
import asyncws
import ssl

@asyncio.coroutine
def echo(websocket):
    while True:
        frame = yield from websocket.recv()
        if frame is None:
            break
        yield from websocket.send(frame)


ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.check_hostname = False
ssl_context.load_cert_chain('example.crt', 'example.key')

loop = asyncio.get_event_loop()
loop.set_debug(True)
server = loop.run_until_complete(
    asyncws.start_server(echo, '127.0.0.1', 8000, ssl=ssl_context))
try:
    loop.run_forever()
except KeyboardInterrupt as e:
    server.close()
    loop.run_until_complete(server.wait_closed())
finally:
    loop.close()