Hi Guy's
I have trouble creating a WebSocket based Connection by using direct Network.framework's NWConnection.
And I don't want to use URLSessions Way!
I Watched the Apple Keynote and it's not working for me.
I'm trying to connect to a public WebSocket Echo Server.
I put the code in a simple playground. Maybe some of you can light me up and explain what is wrong here 'cause i'm not seeing any issue ?!
Thanks and best regards
Vinz
I have trouble creating a WebSocket based Connection by using direct Network.framework's NWConnection.
And I don't want to use URLSessions Way!
I Watched the Apple Keynote and it's not working for me.
I'm trying to connect to a public WebSocket Echo Server.
I put the code in a simple playground. Maybe some of you can light me up and explain what is wrong here 'cause i'm not seeing any issue ?!
Thanks and best regards
Vinz
Code Block swift import UIKit import Network import PlaygroundSupport let parameters = NWParameters.tls let options = NWProtocolWebSocket.Options() parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0) let connection = NWConnection(host: .init("wss://echo.websocket.org/"), port: .https, using: parameters) connection.stateUpdateHandler = { state in switch state { case .ready: print("connection ready") case .failed(let error): print("connection failed with:", error) default: break } } print("start") connection.start(queue: .main) PlaygroundPage.current.needsIndefiniteExecution = true
If you insert this:
at line 13 you’ll see that it prints:
The connection is waiting for DNS to be able to resolve the host you supplied. Clearly echo.websocket.org is correct, so something else is wonky.
The issue here is that you’re constructing your NWConnection with a host and port. This doesn’t work for WebSocket; you need to give it a URL. You do that by replacing line 9 with this:
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Code Block print(state)
at line 13 you’ll see that it prints:
Code Block preparing waiting(-65554: NoSuchRecord)
The connection is waiting for DNS to be able to resolve the host you supplied. Clearly echo.websocket.org is correct, so something else is wonky.
The issue here is that you’re constructing your NWConnection with a host and port. This doesn’t work for WebSocket; you need to give it a URL. You do that by replacing line 9 with this:
Code Block let url = URL(string: "wss://echo.websocket.org/")! let connection = NWConnection(to: .url(url), using: parameters)
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"