I have the following code working just fine. I now need to extract the sending part, so I can return unsolicited data (a struct called currentstatus) back to the client every half second or so. Please will someone show me how to do this?
import Foundation
import NIO
import NIOFoundationCompat
typealias activeCallbackType = (_ active: Bool) -> Void
func activeCallback(_ active: Bool) {
print("channel is \(active ? "active" : "inactive")")
}
final class RequestHandler: ChannelInboundHandler {
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer
private let activeCallback: activeCallbackType
init(_ activeCallback: @escaping activeCallbackType) {
self.activeCallback = activeCallback
}
public func channelActive(context: ChannelHandlerContext) {
self.activeCallback(true)
}
public func channelInactive(context: ChannelHandlerContext) {
self.activeCallback(false)
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let dataIn = self.unwrapInboundIn(data)
do {
let request = try JSONDecoder().decode(RequestAPI.self, from: dataIn)
systemControl.request(request: request)
} catch {
print("Caught receiving in channelRead: \(error)")
}
do {
let allocator = ByteBufferAllocator()
let byteBuffer = try JSONEncoder().encodeAsByteBuffer(currentStatus, allocator: allocator)
context.write(self.wrapOutboundOut(byteBuffer), promise: nil)
} catch {
print("ERROR sending in channelRead: ", error)
}
}
// Flush it out. This can make use of gathering writes if multiple buffers are pending
public func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
// print("func errorCaught: ", error)
context.close(promise: nil)
}
}