Python Websocket Programming
There are many libraries for websocket programming in Python. Among them, the most used one is websockets. This library can be used for both server and client development, and is especially suitable for server use because it can be developed in an asynchronous manner.
And for client programming, the wrbsocket-client library is often used along with websockets.
I will simply create an echo server using websockets and an echo client using sebsocket-client.
Echo Server
import asyncio from websockets.server import serve async def echo(websocket): async for message in websocket: print("RCV ->echo:", message) await websocket.send(message) async def main(): async with serve(echo, "", 8765): await asyncio.Future() # run forever asyncio.run(main())
Echo Client
The part that receives user input can run on an independent thread.
import websocket import time import threading def userinput(): while True: time.sleep(0.5) text = input('Publish Text:') if text: ws.send(text) def on_message(ws, message): print("RCV:",message) def on_error(ws, error): print(error) def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_open(ws): print("Opened connection") ws.send("Hello, World") if __name__ == "__main__": t1 = threading.Thread(target=userinput) t1.daemon = True t1.start() websocket.enableTrace(False) ws = websocket.WebSocketApp("ws://localhost:8765", on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) ws.run_forever()
Test
I will test this by running two Python programs at the same time on the local host.
You can see that it works well.
Wrapping up
To use websockets and websocket-client, install the package using pip (or pip3).
pip3 install websockets pip3 install websocket-client
These two packages also support the WSS protocol with SSL and provide various programming and debugging options.
- Documentation about websockets
- github page for websockets
- Documentation about websocket client
- Github page for websocket client
댓글
댓글 쓰기