Created
April 3, 2025 20:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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