Python Websocket(Build event-driven application)
So , in thistutorial we'll playing with websockets lib for python and create an even-driven application .
create a file called app.py
import asyncio
import websockets
async def handler(websocket):
while True:
message = await websocket.recv()
print(f'message: {message}')
async def main():
print(f'runninc main...')
async with websockets.serve(handler,"",8001):
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main())
Step-by-Step Explanation
- Defining the
main
Coroutine:
async def main():
defines an asynchronous function calledmain
. This function will be the entry point for running our WebSocket server.
- Starting the WebSocket Server:
async with websockets.serve(handler, "", 8001):
useswebsockets.serve
to start a WebSocket server.handler
is a function that will handle incoming WebSocket connections.""
means the server will listen on all available IP addresses.8001
is the port number the server will listen on.- The
async with
syntax ensures that the WebSocket server is properly started and stopped. When the code block underasync with
exits, the server will be shut down.
- Running Forever with
await asyncio.Future()
:
await asyncio.Future()
is used to make themain
coroutine run forever.- Since
asyncio.Future()
creates a Future that is never completed (its result is never set),await asyncio.Future()
will wait indefinitely. - This effectively keeps the server running until the program is terminated.
Why Use await asyncio.Future()
to Run Forever?
Using await asyncio.Future()
is a common trick to keep an async
context running indefinitely. Here’s why:
- Simple and Efficient: By awaiting a Future that never completes, you prevent the
main
coroutine from exiting, which in turn keeps the WebSocket server running. This is a simple and efficient way to ensure the server remains active. - Proper Shutdown Handling: Using the
async with
block ensures that the server is properly shut down when themain
coroutine exits, even if that exit is due to a program termination.
Key Points
- WebSocket Server Setup:
websockets.serve(handler, "", 8001)
sets up the WebSocket server to handle connections withhandler
on port8001
. - Indefinite Running:
await asyncio.Future()
makes sure themain
coroutine runs indefinitely by awaiting a Future that never completes. - Resource Management: The
async with
block ensures that the server is properly managed, starting it when entering the block and shutting it down when exiting.
How to test our websocket
Open a shell, navigate to the directory containing app.py
, and start the server:
python3 app.py
This display "runninc main…" which indicates that the server is running. Let’s make sure that it works.
You cannot test the WebSocket server with a web browser like you test the HTTP server. However, you can test it with websockets’ interactive client.
Now open another shell and run this command:
$ python -m websockets ws://localhost:8001/
You get a prompt. Type a message and press “Enter”. Switch to the shell where the server is running and check that the server received the message. Good!
Sending message from your Browser
now open your devtools and go to console tab and then write the following:
const websocket = new WebSocket('ws://localhost:8001')
//sending message
websocket.send(JSON.stringify({type:"move_peace", moveLeft: 3}))
after do this go to your shell where you main app.py is running and check the message tha was sent there.you'll will end up with something like the image below