NIOTS TCP Chat Client

Hey everyone, I am trying to write a TCP Chat Client with NIOTS. I am having issues passing the data from the Chat Handler to my Client Socket File where my bootstrap is located. The goal is to pass the data I get back from the server to the Client File and then the app can call clientSocket.receivedData() in order to feed the data into the UI. Any suggestions on the best practice of passing data from channelRead() to my Client File? I feel like I have been staring at a screen too long and the answer is obvious. Thank you for your help and patience.

What type of object is your "Client Socket File"?

It's a public class where I create the bootstrap, I have a method to run the program, I have a method to shut down the program, and I have a method that will send data to the tcp server.

public class NIOSocketConnection {

private var chatHandler = ChatHandler()
public var onDataReceived: ServerDataReceived? = nil

func clientBootstrap() -> NIOTSConnectionBootstrap {}

func run() throws {}

func shutdown() {}

func send(message: Data) {}

    func dataReceived(completion: @escaping (ServerDataReceived?) throws -> Void) {
    chatHandler.dataReceived = onDataReceived
    try? completion(onDataReceived)
}

}

My chat handler basically looks like this. I am not sure this Is the correct approach.

public typealias ServerDataReceived = (ChatData) -> ()

class ChatHandler: ChannelOutboundHandler, ChannelInboundHandler {

public var dataReceived: ServerDataReceived?

    public func channelRead(context: ChannelHandlerContext, data: NIOAny){
    switch self.currentlyWaitingFor {
    case .dataFromServer:
        var result = self.unwrapInboundIn(data)
        let readableBytes = result.readableBytes
        if let received = result.readData(length: readableBytes) {
            
//dataReceived is always is nil so never runs
            if let dataReceived = dataReceived {
                print(dataReceived, "2")
                let chatData = ChatData(data: received)
                dataReceived(chatData)
            }
        }
    case .error(let error):
        fatalError("We have a fatal receiving data from the server: \(error)")
    }
}
}

So in this instant you can pass the callback you want to receive the data into the init of ChatHandler.

Works great thank you

Terms of Service

Privacy Policy

Cookie Policy