Using two network protocol framer in the protocols stack

Hello, I wrote a server and client using the Network framework and added the same protocol framer on both sides. It seems to work just fine.

But then I wanted to add another protocol framer in the stack and things stop working. I can see that both protocols are started but for some reason the protocol at index 1 does not receive output on the client side and the server receives nothing.

For purpose of testing I have simply duplicated and renamed the first protocol (which I know worked by itself) in order to create the second protocol. So I am not sure what's going on here. Any idea?

Interesting. When I debug this sort of thing I like to configure it on the client and send a packet to the server and print out the bytes received. For example, if you are able to print out the byte stream on the server then you should be able to get a look at which protocol is being used on the connection. For a type, length, value protocol, you could alter each protocol on the client to be defined slightly different and when you read bytes off the stream on the server you can print them from top to bottom and see which protocol you are using.

Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com

Thanks for your reply. The server receives nothing, none of the protocol has its handleInput() method called. Here are the logs:

# Client

Protocol1 start()
Protocol2 start()
sending 2990 bytes
Protocol2 handleOutput()

# Server

Protocol1 start()
Protocol2 start()

Protocol1 is placed at index 1, Protocol2 is on top at index 0. Instead I would expect this to happen:

# Client

Protocol1 start()
Protocol2 start()
sending 2990 bytes
Protocol2 handleOutput()
Protocol1 handleOutput()

# Server

Protocol1 start()
Protocol2 start()
Protocol1 handleInput()
Protocol2 handleInput()
received 2990 bytes

I insert the protocols on the NWListener (server-side) and the NWConnection (client-side) like so:

let protocol1 = NWProtocolFramer.Options(definition: Protocol1.definition)
let protocol2 = NWProtocolFramer.Options(definition: Protocol2.definition)

let parameters: NWParameters = .tcp
parameters.defaultProtocolStack.applicationProtocols.insert(protocol1, at: 0)
parameters.defaultProtocolStack.applicationProtocols.insert(protocol2, at: 0)

If that helps, my handleOuptut() method looks like this:

func handleOutput(framer: NWProtocolFramer.Instance, message: NWProtocolFramer.Message, messageLength: Int, isComplete: Bool) {
    print("Protocol2 handleOutput()")
    
    var length = Int32(messageLength)
    let data = Data(bytes: &length, count: MemoryLayout<Int32>.size)
    
    framer.writeOutput(data: data)
    
    try? framer.writeOutputNoCopy(length: messageLength)
}
Using two network protocol framer in the protocols stack
 
 
Q