WebSocket连接异常关闭(错误码1006)问题求助
Hey there! Sorry you're stuck with this 1006 WebSocket error—it's super frustrating when connections drop without a clear reason. Let's walk through some common fixes based on your code and the issue you're facing:
First, Fix the Obvious: Your Empty stream_url
Looking at your code, you've set stream_url=""—that's definitely a problem! WebSocket connections require a valid ws:// or wss:// URI. Start by replacing that empty string with the actual streaming URL provided by your service.
Check Your Authentication Headers
The extra_headers parameter needs to follow HTTP header rules for WebSocket handshakes. Here are a few things to verify:
- Make sure
gives_authreturns a proper dictionary of headers (e.g.,{"Authorization": "Bearer YOUR_TOKEN"}). Print the headers and double-check for typos or invalid characters. - Avoid headers that aren't allowed in WebSocket handshakes (like
Content-LengthorTransfer-Encoding—these are handled automatically by thewebsocketslibrary). - Test with a minimal set of headers first (just the auth token if needed) to rule out header-related issues.
Add Subscription Logic (If Required)
Many streaming WebSocket servers expect you to send a subscription message immediately after the handshake completes. If you don't send this, the server might close the connection with a 1006 error because it has no data to send you. Here's an updated version of your function with this logic:
async def streaming_data(url): headers = await gives_auth(auth_url) print(headers) try: async with websockets.client.connect(url, extra_headers=headers) as websocket: # Send subscription message (adjust this to match your service's format) await websocket.send('{"action": "subscribe", "streams": ["your-target-stream"]}') # Keep listening for incoming messages (instead of just one recv) async for message in websocket: print("Received data:", message) except websockets.exceptions.InvalidHandshake: print('Exception raised when a handshake request or response is invalid.') except websockets.exceptions.InvalidURI: print('Exception raised when an URI isn’t a valid websocket URI.') except websockets.exceptions.InvalidStatusCode as e: print(f'Handshake response status code is invalid: {e.status_code}') except websockets.exceptions.ConnectionClosedError as e: print(f'Connection closed with error: Code {e.code}, Reason: {e.reason}') except Exception as e: print('Error in making the Websocket Connection!!') print(str(e))
Improve Error Logging
Your current error handling is a bit too broad. Catching specific websockets exceptions (like ConnectionClosedError) will give you way more detailed info about why the connection dropped, which is far more helpful than just printing e.args.
Simplify Your Event Loop Setup
Instead of manually creating a new event loop, use asyncio.run() (available in Python 3.7+) for cleaner, more maintainable code:
async def main(): stream_url = "wss://your-actual-stream-url.com" # Replace with real URL! await streaming_data(stream_url) if __name__ == "__main__": import asyncio asyncio.run(main())
Other Quick Checks
- Ensure your network isn't blocking WebSocket traffic (some firewalls or proxies block
ws/wssports). - Verify the server is up and running, and the stream you're trying to subscribe to actually exists.
内容的提问来源于stack exchange,提问作者iamklaus




