Skip to content

Commit

Permalink
fix example, fix server (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
circuitsacul authored Dec 9, 2022
1 parent 1c8e060 commit b4aa843
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 10 deletions.
14 changes: 14 additions & 0 deletions example/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import sys

from example import client, server

if __name__ == "__main__":
if len(sys.argv) == 2:
if sys.argv[1] == "client":
client.run()
exit(0)
elif sys.argv[1] == "server":
server.run()
exit(0)
print("Usage: python -m example [client|server]")
exit(-1)
16 changes: 10 additions & 6 deletions example/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from concurrent.futures import ThreadPoolExecutor

from example.events import Message
from socketapp import Client
Expand All @@ -7,7 +8,9 @@
async def send(client: Client) -> None:
await client.wait_until_ready()
while True:
await client.send(Message(data="hi"), client.clients)
with ThreadPoolExecutor(1, "AsyncInput") as executor:
inp = await asyncio.get_event_loop().run_in_executor(executor, input)
await client.send(Message(data=inp), client.clients)
await asyncio.sleep(1)


Expand All @@ -16,8 +19,9 @@ async def main(client: Client) -> None:
await client.run()


try:
client = Client()
asyncio.run(main(client))
finally:
client.stop()
def run() -> None:
try:
client = Client()
asyncio.run(main(client))
finally:
client.stop()
4 changes: 3 additions & 1 deletion example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
from example import events # noqa
from socketapp import Server

asyncio.run(Server().run())

def run() -> None:
asyncio.run(Server().run())
7 changes: 4 additions & 3 deletions socketapp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,21 @@ def __init__(

self.clients: dict[int, WebSocketServerProtocol] = {}

self.future: asyncio.Future[None] = asyncio.Future()
self.future: asyncio.Future[None] | None = None

async def run(self) -> None:
asyncio.get_event_loop().add_signal_handler(signal.SIGINT, self.stop)

if self.future.done():
if not self.future or self.future.done():
self.future = asyncio.Future()

asyncio.create_task(self._broadcast_clients())
async with serve(self._serve, self.host, self.port):
await self.future

def stop(self) -> None:
self.future.set_result(None)
if self.future and not self.future.done():
self.future.set_result(None)

async def _handshake(self, ws: WebSocketServerProtocol) -> int | None:
init = await ws.recv()
Expand Down

0 comments on commit b4aa843

Please sign in to comment.