Receive message on WebSocket stream

Hi, I'm using Network Framework to make a peer-to-peer connection between two devices over a WebSocket bytestream. I was wondering, should there be any special logic in my receiveMessage(completion:) code in NWConnection, since I'm using the WebSocket protocol?
Here are some snippets of my code:

Code Block swift
(NWConnection)
var connection: NWConnection
let parameters = NWParameters.tls
parameters.includePeerToPeer = true
let websocketOptions = NWProtocolWebSocket.Options()
websocketOptions.autoReplyPing = true
parameters.defaultProtocolStack.applicationProtocols.insert(websocketOptions, at: 0)
let connection = NWConnection(to: endpoint, using: parameters)
startConnection()
func startConnection() {
connection.stateUpdateHandler = { newState in
        switch newState {
case .ready:
log("Connection \(connection) established")
self.receiveMessage()
// Handle the rest
}
}

Here's my receiveMessage code:
Code Block swift
func receiveMessage() {
connection.receiveMessage { [unowned self] (content, context, isComplete, error) in
if let error = error {
log("Error while receiving data\(error)")
return
}
if let data = content {
didReceiveMessage(data)
if let context?.isFinal != nil {
didFinishReceiving()
}
}
self.receiveMessage()
}
}

Do WebSocket messages have additional metadata that I need to filter through in my receiveMessage function? Or does content already have just the data I want?


I just ran through this locally and you could dig around in the NWConnection.ContentContext to see if there is anything set there for the NWProtocolWebSocket defintion.

Code Block
if let responseMessage = context?.protocolMetadata(definition: NWProtocolWebSocket.definition) {
...
}


This may give you something based on how your WebSocket is setup.

Also note the send side of this which would include adding the context that could look something like:

Code Block
let message = NWProtocolWebSocket.Metadata(opcode: .text)
let context = NWConnection.ContentContext(identifier: "my_identifier", metadata: [message])


Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
Ok, I'll look into that, thanks!
Receive message on WebSocket stream
 
 
Q