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