42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
|
import asyncio
|
||
|
import websockets
|
||
|
|
||
|
|
||
|
async def websocket_client(uri):
|
||
|
"""
|
||
|
A simple WebSocket client that connects to a specified URI,
|
||
|
sends a message, receives data, and prints status codes.
|
||
|
"""
|
||
|
try:
|
||
|
async with websockets.connect(uri) as websocket:
|
||
|
print(f"WebSocket connection established. Status code: {websocket.response.status_code}")
|
||
|
|
||
|
message = "Hello from client!"
|
||
|
await websocket.send(message)
|
||
|
print(f"Sent message: {message}")
|
||
|
|
||
|
try:
|
||
|
async for message in websocket: # Iterate through incoming messages
|
||
|
print(f"Received message: {message}")
|
||
|
except websockets.exceptions.ConnectionClosedError as e:
|
||
|
print(f"Connection closed with code {e.code} and reason: {e.reason}")
|
||
|
except Exception as e:
|
||
|
print(f"An unexpected error occurred: {e}")
|
||
|
|
||
|
except websockets.exceptions.InvalidStatusCode as e:
|
||
|
print(f"Connection failed with status code {e.status_code} and reason: {str(e)}")
|
||
|
except OSError as e:
|
||
|
print(f"OSError: {e}") # Handle potential OS errors like connection refused
|
||
|
except Exception as e:
|
||
|
print(f"An unexpected error occurred during connection: {e}")
|
||
|
|
||
|
|
||
|
async def main():
|
||
|
uri = "wss://wsdebug.tiefen.fun/ws" # Example WebSocket echo server
|
||
|
# uri = "wss://your_websocket_server_url" # Replace with your server URL if needed. Note 'wss' for secure connections.
|
||
|
await websocket_client(uri)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
asyncio.run(main())
|