如何通过Starscream检查Socket连接状态?isConnecting为私有属性
isConnecting is Private) Hey there! I’ve dealt with this exact scenario using Starscream before, so I know how frustrating it can be when the isConnecting property is off-limits. Here are two reliable ways to check the connecting state:
1. Track State Manually via Delegate Methods (Works for All Versions)
Since we can’t access the private isConnecting flag, we can maintain our own state variable and update it using Starscream’s delegate callbacks. This is a safe approach that works across all Starscream versions.
Here’s a code example:
import Starscream class SocketHandler: WebSocketDelegate { private var webSocket: WebSocket! private var isSocketInConnectingState = false init(socketURL: URL) { let request = URLRequest(url: socketURL) webSocket = WebSocket(request: request) webSocket.delegate = self } func initiateConnection() { // Mark as connecting right before calling connect() isSocketInConnectingState = true webSocket.connect() } // MARK: - WebSocketDelegate Methods func didConnect(socket: WebSocket) { // Connection succeeded, reset the flag isSocketInConnectingState = false print("WebSocket connected!") } func didDisconnect(socket: WebSocket, error: Error?) { // Connection failed or disconnected, reset the flag isSocketInConnectingState = false let message = error != nil ? "Disconnected with error: \(error!.localizedDescription)" : "Disconnected normally" print(message) } func didReceiveError(socket: WebSocket, error: Error) { // Any connection error means we're no longer connecting isSocketInConnectingState = false print("Connection error: \(error.localizedDescription)") } // Helper method to expose the connecting state func isConnecting() -> Bool { return isSocketInConnectingState } }
2. Use the Public state Property (Recommended for Newer Versions)
If you’re using Starscream 4.0 or later, the framework provides a public state property of type WebSocketState (an enum). This enum includes a .connecting case that directly tells you if the socket is in the process of establishing a connection.
You can check it with a simple condition:
if webSocket.state == .connecting { print("WebSocket is currently trying to connect") }
The WebSocketState enum also includes other useful states like .connected, .disconnected, and .failed, making it a great all-around tool for tracking socket status.
Important Note
Avoid using KVO to observe the private isConnecting property. Private APIs can change without warning in future Starscream updates, which would break your code. Stick to the supported methods above!
内容的提问来源于stack exchange,提问作者Maiko Ohkawa




