You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Starscream建立WebSocket连接时出现Invalid HTTP upgrade错误

Fixing "Invalid HTTP upgrade" Error in Swift WebSocket Connection

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: websocket
  • Connection: Upgrade
  • Sec-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:45:32