Open nandarosyadi opened 5 months ago
Have you try sending auth token data right after your socket connection was open?
Thank you for the quick response. Server request to send the auth when starting connection, so it need to send when the connect() method called. Is there any way to do that in current version?
If your token on header and sent during handshake you can try add your token in options during initialization
NWWebSocket(url: socketURL, options: options)
where
options.setAdditionalHeaders([("header_key","your_token")])
let options = NWWebSocket.defaultOptions
options.setAdditionalHeaders([("header_key","your_token")])
NWWebSocket(url: socketURL, options: options)
Hey @ajinumoto, thanks for the help. Now, I can send my auth but the socket is not connected yet. It's not called the delegate method, so what's wrong here?
Here is my code
func connectSocket() {
guard let accessJWT: String = UserDefaultManager.getUserDefault(key: .userData_AccessJWT) else {
self.delegate.socketDidError(message: "Token socket not found")
return
}
self.socketManager?.delegate = self
let socketOption = NWProtocolWebSocket.Options()
socketOption.setAdditionalHeaders([("token", accessJWT)])
self.socketManager = NWWebSocket(url: self.socketURL,
connectAutomatically: true,
options: socketOption,
connectionQueue: .main)
self.socketManager?.ping(interval: 15)
func webSocketDidConnect(connection: WebSocketConnection) {
print("Socket: Connected")
self.socketManager?.ping(interval: 15)
}
func webSocketDidDisconnect(connection: WebSocketConnection,
closeCode: NWProtocolWebSocket.CloseCode, reason: Data?) {
print("Socket: Disconnected")
self.connectSocket()
}
func webSocketDidConnect(connection: WebSocketConnection) {
print("Socket: Connected")
self.socketManager?.ping(interval: 15)
}
Probably because you set
self.socketManager?.delegate = self
before
self.socketManager = NWWebSocket(url: self.socketURL, connectAutomatically: true, options: socketOption, connectionQueue: .main)
so your delegate is still on old self.socketManager
value (or nil)
I've move the delegate after the NWWebSocket initialization, but the delegate method is not called either
self.socketManager = NWWebSocket(url: self.socketURL,
connectAutomatically: true,
options: socketOption,
connectionQueue: .main)
self.socketManager?.delegate = self
self.socketManager?.ping(interval: 15)
but the delegate method is not called
All delegate not working really, even the connect and disconnect delegate? If all of delegate are not working, there is something wrong with your code. If you didn't receive message from socket try listen using self.socketManager?.listen()
?
Btw, i highly recommend you to see NWWebSocket
class for deeper understanding about this library
Server need to receive auth token from client, so it needs to send the auth. Is there any ways to add auth in socket request? Thank you