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)
}