Skip to content

Instantly share code, notes, and snippets.

@liuliu
Created April 3, 2025 20:54
Show Gist options
  • Save liuliu/079e3c4c1fd71488fc64f2b8413c81b0 to your computer and use it in GitHub Desktop.
Save liuliu/079e3c4c1fd71488fc64f2b8413c81b0 to your computer and use it in GitHub Desktop.
MonitoringFramer, still don't know what's the best way to insert into NIOTransportServices.
// First, define our monitoring framer
class MonitoringFramer: NWProtocolFramerImplementation {
func wakeup(framer: NWProtocolFramer.Instance) {
}
func stop(framer: NWProtocolFramer.Instance) -> Bool {
return true
}
func cleanup(framer: NWProtocolFramer.Instance) {
}
// Protocol definition
static let definition = NWProtocolFramer.Definition(implementation: MonitoringFramer.self)
// Required protocol identifier
static var label: String { return "MonitoringFramer" }
// Each connection needs its own instance of the framer
required init(framer: NWProtocolFramer.Instance) {
self.framerInstance = framer
}
private let framerInstance: NWProtocolFramer.Instance
// Start point for monitoring outgoing messages
func start(framer: NWProtocolFramer.Instance) -> NWProtocolFramer.StartResult {
return .ready
}
// Handle incoming messages
func handleInput(framer: NWProtocolFramer.Instance) -> Int {
_ = framer.parseInput(minimumIncompleteLength: 1, maximumLength: 65535) { buffer, endOfMessage in
if let buffer = buffer {
_ = framer.deliverInputNoCopy(length: buffer.count, message: .init(instance: framer), isComplete: endOfMessage)
logReceived(messageLength: buffer.count)
}
return 0
}
return 0
}
// Handle outgoing messages
func handleOutput(framer: NWProtocolFramer.Instance, message: NWProtocolFramer.Message, messageLength: Int, isComplete: Bool) {
// Get data the application wants to send
try? framer.writeOutputNoCopy(length: messageLength)
logSent(messageLength: messageLength)
}
// MARK: - Logging Methods
private func logSent(messageLength: Int) {
let timestamp = Date()
print("[\(timestamp)] SENT [\(messageLength) bytes]")
}
private func logReceived(messageLength: Int) {
let timestamp = Date()
print("[\(timestamp)] RECEIVED [\(messageLength) bytes]")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment