0

I need to send and then receive some data(string) from/to UDP client. I can send data to client with code below but how can I implement read data as well? I have read thousands pages and examples but I just can not figure it out. Can someone please modify my code so it will be capable sent and than received data from UDP device?

My code is from here: How to implement UDP client and send data in Swift on iPhone?

Details: I am sending string to ESP32 device with specific IP and port. then this device will do some calculations and return some data(string) back. So I will need receive that data after I sent data string to it. I am able to sent string with provided code below but I do not know how to modify for receiving data from my ESP32 device as well via UDP.

import Foundation

func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) {


func htons(value: CUnsignedShort) -> CUnsignedShort {
    return (value << 8) + (value >> 8);
}

let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP

let addr = sockaddr_in(
    sin_len:    __uint8_t(MemoryLayout<sockaddr_in>.size),
    sin_family: sa_family_t(AF_INET),
    sin_port:   htons(value: port),
    sin_addr:   address,
    sin_zero:   ( 0, 0, 0, 0, 0, 0, 0, 0 )
)

let sent = textToSend.withCString { cstr -> Int in

    var localCopy = addr

    let sent = withUnsafePointer(to: &localCopy) { pointer -> Int in
        let memory = UnsafeRawPointer(pointer).bindMemory(to: sockaddr.self, capacity: 1)
        let sent = sendto(fd, cstr, strlen(cstr), 0, memory, socklen_t(addr.sin_len))
        return sent
    }

    return sent
}

close(fd)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
marigu
  • 1
  • 2
  • Have a look at https://github.com/robbiehanson/CocoaAsyncSocket – vadian May 13 '19 at 17:09
  • Do you have any particular OS requirements? There's a new [Network framework](https://developer.apple.com/documentation/network) that looks promising, but available only on iOS 12+ and macOS 10.14+. – Caleb May 13 '19 at 21:48
  • Actually I have managed it with CocoaAsyncSocket but I have another problem, I can not change label text with received data, I have described it here: https://stackoverflow.com/questions/56203943/cocoaasyncsocket-how-change-label-text-with-received-data-via-udp – marigu May 19 '19 at 00:55

0 Answers0