0

I am trying to send an image via an UDP connection.

class Connect: NSObject {
    var connection: NWConnection?
    
    func connectToUDP(host: String, port: UInt16) {
        let host = NWEndpoint.Host(host)
        guard let port = NWEndpoint.Port(rawValue: port) else { return }
        let messageToUDP = "Bonjour"
        
        connection = NWConnection(host: host, port: port, using: .udp)
        
        connection?.stateUpdateHandler = { (newState) in
            print("This is stateUpdateHandler:")
            switch (newState) {
            case .ready:
                print("State: Ready\n")
                self.sendUDP(messageToUDP)
                self.receiveUDP()
            default:
                print("ERROR! State not defined!\n")
            }
        }
        connection?.start(queue: .global())
    }
    
    func sendUDP(_ content: Data) {
        connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Data was sent to UDP")
            } else {
                print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
            }
        })))
    }
   }

I converted the image into data and when I send it :

guard let image = UIGraphicsGetImageFromCurrentImageContext(),
let data = image.pngData() else { return }
connect.connectToUDP(host: "192.168.XX.XX", port: 10000)
connect.sendUDP(data)

I got this error

ERROR! Error when data (Type: Data) sending. NWError: POSIXErrorCode: Message too long

How can I split the data in packets and in order the data get fully reconstructed by the receiver ?

Blisko
  • 107
  • 2
  • 9
  • check [this](https://stackoverflow.com/questions/26571640/how-to-transfer-jpg-image-using-udp-socket) – Kofi Dec 29 '21 at 14:34
  • UDP can only send messages with length bigger than 65535 bytes. You will have to split your data in packets with some header to be able to reconstruct full data by the receiver. You can have information in this [thread](https://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet) – Ptit Xav Dec 29 '21 at 14:38

0 Answers0