xxxxxxxxxx
import asyncio
import websockets
async def handle_websocket(websocket, path):
# This function will handle incoming WebSocket connections
try:
while True:
message = await websocket.recv()
# Process the received message
# ...
# Send a response
response = "Hello from the server!"
await websocket.send(response)
except websockets.exceptions.ConnectionClosedError:
# Handle client disconnect
pass
# Start the WebSocket server
start_server = websockets.serve(handle_websocket, 'localhost', 8765)
# Run the server indefinitely
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
xxxxxxxxxx
#!/usr/bin/env python
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
xxxxxxxxxx
import websocket
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("WebSocket connection closed")
def on_open(ws):
ws.send("Hello, WebSocket!")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()