使用Starscream建立WebSocket连接时出现Invalid HTTP upgrade错误
Hey there, let's work through that "Invalid HTTP upgrade" error you're hitting with your WebSocket connection. After looking over your code, I can spot a couple of critical issues that are almost certainly causing this problem:
1. Wrong HTTP Method for WebSocket Handshake
WebSocket connections require a GET request for the initial handshake, but you've set request.httpMethod = "POST" in your code. This directly breaks the WebSocket protocol specification, which expects a GET request to trigger the HTTP upgrade to WebSocket.
2. Missing WebSocket Protocol Headers
While most WebSocket libraries auto-add the mandatory handshake headers, using a POST method would prevent this from working correctly. The required headers for a valid WebSocket upgrade include:
Upgrade: websocketConnection: UpgradeSec-WebSocket-Key(auto-generated by libraries like Starscream)Sec-WebSocket-Version: 13
Switching to GET should let your WebSocket class (I’m guessing this is the Starscream library, a popular Swift WebSocket implementation) handle these headers automatically.
3. Verify Your URL Scheme
Make sure your WebSocket URL uses the correct protocol prefix:
- Use
ws://for unencrypted connections - Use
wss://for encrypted (SSL/TLS) connections
Avoid http:// or https://—those are for regular HTTP requests, not WebSocket.
Corrected Code Example
Here’s how to adjust your code to fix these issues:
// Replace with your actual WebSocket URL (ws:// or wss://) guard let socketUrl = URL(string: "ws://your-server-url.com/websocket-endpoint") else { print("Invalid WebSocket URL provided") return } var request = URLRequest(url: socketUrl) request.timeoutInterval = 2.0 // WebSocket handshake requires GET method request.httpMethod = "GET" // Keep your Authorization header as needed request.setValue("header", forHTTPHeaderField: "Authorization") socket = WebSocket(request: request) socket.delegate = self socket.connect()
Additional Troubleshooting Tips
- Check Server Configuration: Ensure your backend server is set up to handle WebSocket upgrade requests. It should accept GET requests on your target endpoint and support the WebSocket protocol.
- Library Version: If you’re using Starscream, make sure you’re on the latest version—older releases might have handshake-related bugs.
- Network Restrictions: Some firewalls or proxies block WebSocket traffic. Test your connection on a different network (like mobile data) to rule this out.
内容的提问来源于stack exchange,提问作者Sandip Gill

