NWConnection Websocket send error

I'm attempting to use NWConnection as a websocket given a NWEndpoint returned by NWBrowser, setup like:

    let tcpOptions = NWProtocolTCP.Options()
    tcpOptions.enableKeepalive = true
    tcpOptions.keepaliveIdle = 2
    let parameters = NWParameters(tls: nil, tcp: tcpOptions)
    parameters.allowLocalEndpointReuse = true
    parameters.includePeerToPeer = true
    let options = NWProtocolWebSocket.Options()
    options.autoReplyPing = true
    options.skipHandshake = true

    parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0)
    self.connection = NWConnection(to: endpoint, using: parameters)

The initial connection does make it to the ready state but when I first try to send a text message over the websocket, i get

nw_read_request_report [C1] Receive failed with error "Input/output error"
nw_flow_prepare_output_frames Failing the write requests [5: Input/output error]
nw_write_request_report [C1] Send failed with error "Input/output error"

immediately, and the websocket is closed. Send code here:

      let encoder = JSONEncoder()
      let dataMessage = try encoder.encode(myMessage)
      let messageMetadata = NWProtocolWebSocket.Metadata(opcode: .text)
      let context = NWConnection.ContentContext(identifier: "send", metadata: [messageMetadata])
      connection.send(content: dataMessage, contentContext: context, completion: .contentProcessed({ error in
        if let error = error {
          print (error)
        }
      }))

What would typically cause the Input/output error when writing? Am I doing something obviously wrong or is there something else I can do to get additional debug information?

Thanks in advance for any help.

when I first try to send a text message over the websocket, i get [an error]

Hmmmm, this is working for me.

Looking at your code I can’t see anything obviously broken. The one thing I did notice is that you’re setting skipHandshake. Did you do that at both ends? If not, make sure you do. Alternatively, remove that setting at both ends and see if that improves things.

Also, what OS version are you testing this on? I’m working on macOS 14.7.1.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

NWConnection Websocket send error
 
 
Q