import Foundation
import Network
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let connection = NWConnection(host: "::1", port: 6060, using: .udp)
func send(data: Data?, using connection: NWConnection) {
connection.send(content: data, contentContext: .defaultMessage, isComplete: true, completion: .contentProcessed({ (e) in
print(e)
}))
}
connection.stateUpdateHandler = { state in
print(state)
if state == .ready {
send(data: Data(bytes: [255]), using: connection)
}
}
connection.start(queue: .main)
Running the playgorund I capture the proper frame with wireshark and the snippet prints
preparing
ready
nil
as expected.
While trying to send an empty or nil data (in code line 15 above), independent from contentContext and isComplete parameters in line 08, I don't capture any frame with wireshark and the playground prints the same
preparing
ready
nil
For 'reference' this playground snippet (using socket library) works as expected
import Foundation
import Darwin
let data = Data(bytes: [])
let nsData = data as NSData
let rawPtr = nsData.bytes
let length = nsData.length
var hints = addrinfo()
var paddr: UnsafeMutablePointer?
defer {
if paddr != nil { freeaddrinfo(paddr) }
}
hints.ai_family = AF_INET6
hints.ai_socktype = SOCK_DGRAM
hints.ai_flags = AI_ADDRCONFIG
// to avoid fill addrinfo manualy :-)
if getaddrinfo("::1", "6060", &hints, &paddr) != 0 {
print(errno)
exit(0)
}
if paddr?.pointee.ai_next != nil {
print("it must be only one addrinfo with ::1 address")
exit(0)
}
let sock = socket(paddr!.pointee.ai_family, paddr!.pointee.ai_socktype, paddr!.pointee.ai_protocol)
if sock < 0 {
print(errno)
exit(0)
}
if sendto(sock, rawPtr, length, 0, paddr!.pointee.ai_addr, paddr!.pointee.ai_addrlen) < 0 {
print(errno)
exit(0)
} else {
print("packet with", nsData, "payload sent successfully")
}