Skip to content

Instantly share code, notes, and snippets.

@michael94ellis
Last active December 24, 2022 13:09
Show Gist options
  • Save michael94ellis/8d3171fbef897c9af8db7b7491d97601 to your computer and use it in GitHub Desktop.
Save michael94ellis/8d3171fbef897c9af8db7b7491d97601 to your computer and use it in GitHub Desktop.
//
// UDPClient.swift
//
import Network
import Foundation
protocol UDPListener {
func handleResponse(_ client: UDPClient, data: Data)
}
class UDPClient {
var connection: NWConnection
var address: NWEndpoint.Host
var port: NWEndpoint.Port
var delegate: UDPListener?
var resultHandler = NWConnection.SendCompletion.contentProcessed { NWError in
guard NWError == nil else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
return
}
}
init?(address newAddress: String, port newPort: Int32) {
guard let codedAddress = IPv4Address(newAddress),
let codedPort = NWEndpoint.Port(rawValue: NWEndpoint.Port.RawValue(newPort)) else {
print("Failed to create connection address")
return nil
}
address = .ipv4(codedAddress)
port = codedPort
connection = NWConnection(host: address, port: port, using: .udp)
connection.stateUpdateHandler = { newState in
switch (newState) {
case .ready:
print("State: Ready")
return
case .setup:
print("State: Setup")
case .cancelled:
print("State: Cancelled")
case .preparing:
print("State: Preparing")
default:
print("ERROR! State not defined!\n")
}
}
connection.start(queue: .global())
}
deinit {
connection.cancel()
}
func send(_ data: Data) {
self.connection.send(content: data, completion: self.resultHandler)
self.connection.receiveMessage { data, context, isComplete, error in
guard let data = data else {
print("Error: Received nil Data")
return
}
guard self.delegate != nil else {
print("Error: UDPClient response handler is nil")
return
}
self.delegate?.handleResponse(self, data: data)
}
}
}
class UDPMessageReader: UDPListener {
var commandClient = UDPClient(address: IPAddress, port: CommandPort)
init() {
commandClient.delegate = self
}
func handleResponse(_ client: UDPClient, data: Data) {
// Do Something
}
}
@riley-williams
Copy link

👍🏻

@nkmakerin
Copy link

Hii Michael,
I am using IPad Pro with swiftplayground app.. I do not have access to MacBook n Xcode..
Can you please share some snippet about how to encapsulate udp sender receiver class you hv made in to swiftplayground app on iPad to make use of it.. I hv just migrated to Apple echo system and want to communicate with Tello drone via udp using swiftplayground app on ipad
Marry Christmas in advance..
Cheers

nkmaker

@michael94ellis
Copy link
Author

michael94ellis commented Dec 24, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment