server.py

Asyncio import websockets import time """ async def echo(websocket, path): while True: now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) await websocket.send(now) await asyncio.sleep(2) if __name__ == '__main__': Start_server = websockets. Serve (echo,'127.0.0.1',5000) # Change your own address asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()

client.py

import asyncio import websockets async def hello(uri): async with websockets.connect(uri) as websocket: while True: Recv_text = await websocket.recv() # print(recv_text) if __name__ == '__main__': Asyncio.get_event_loop ().run_until_complete(hello('ws://127.0.0.1:5000')) # Change your own address
  1. PIP installwebsockets
  2. To start the firstserver.pyAnd then startclient.py.
  3. Effect:

Show it on the web. client.html

<! DOCTYPE html> <html> <head> <title>WebSocket demo</title> </head> <body> <script> var ws = new WebSocket (ws: / / 127.0.0.1:5000 "/"), the messages = document. The createElement method (" ul "); ws.onmessage = function (event) { var messages = document.getElementsByTagName('ul')[0], message = document.createElement('li'), content = document.createTextNode(event.data); message.appendChild(content); messages.appendChild(message); }; document.body.appendChild(messages); </script> </body> </html>

Start server.py and then click on the page.


Reference:


https://websockets.readthedoc…