Custom protocol options

I'm trying to define a custom protocol using NWProtocolFramer.


I have tried to add options for the protocol by extending NWProtocolFramer.Options, but unlike NWProtocolFramer.Message, there appears to be nowhere to store values.


What is the correct way of adding options?


David

Adding NWProtocolFramer.Options can be added to a NWConnection's NWParameters during the initial connection definition. For NWProtocolFramer this can be done using a definition like so:


// Create a class that implements a framing protocol.
class GameProtocol: NWProtocolFramerImplementation {
  // Create a global definition of your game protocol to add to connections.
  static let definition = NWProtocolFramer.Definition(implementation: GameProtocol.self)


  ...
}

extension NWParameters {
  convenience init(passcode: String) {
  ...
  let gameOptions = NWProtocolFramer.Options(definition: GameProtocol.definition)
  self.defaultProtocolStack.applicationProtocols.insert(gameOptions, at: 0)
  }
}

For more information, check out the Building a Custom Peer-to-Peer Protocol sample for more on the GameProtocol definition.


Matt Eaton

DTS Engineering, CoreOS

meaton3 at apple.com

I have a version of this code. What I want to do is add specific options that I can use, e.g.,


let gameOptions = NWProtocolFramer.Options(definition: GameProtocol.definition) 
gamesOptions.isServer= true
self.defaultProtocolStack.applicationProtocols.insert(gameOptions, at: 0)


The following extension makes this code compile, but I have no way to record the value.


extension NWProtocolFramer.Options {
   
    var isServer: Bool {
        get {  true
           
        }
        set {
        }
    }

}

It looks like you may be controlling the client and server in your architecture. Doing so could allow you to control the context from the connection level and set specifics in the NWProtocolFramer.Message extension. For example, you could try:


extension NWProtocolFramer.Message {
  convenience init(otherData: String, serverFrame: Bool) {
     self.init(definition: CustomFrame.definition)
     self.serverFrame = serverFrame
  }

  var serverFrame: Bool {
     get {
         if let server = self["serverFrame"] as? Bool {
             return server
         } else {
             return false
         }
     }
     set {
         self["serverFrame"] = newValue
     }
  }

  ...
}


Which then allows you to set metadata on the context say before data is sent or read.


let message = NWProtocolFramer.Message(otherData: contextData, serverFrame: true)
let context = NWConnection.ContentContext(identifier: contextData,
                                          metadata: [message])


Matt Eaton

DTS Engineering, CoreOS

meaton3 at apple.com

Custom protocol options
 
 
Q