Skip to content

Instantly share code, notes, and snippets.

@michael94ellis
Created June 1, 2020 14:41
Show Gist options
  • Save michael94ellis/da397a69a92a4db264ac62c017580e76 to your computer and use it in GitHub Desktop.
Save michael94ellis/da397a69a92a4db264ac62c017580e76 to your computer and use it in GitHub Desktop.
iOS 12 Network Framework UDP Client Example
import Network
import Foundation
class UDPClient {
var connection: NWConnection
var address: NWEndpoint.Host
var port: NWEndpoint.Port
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
}
self.address = .ipv4(codedAddress)
self.port = codedPort
self.connection = NWConnection(host: .ipv4(codedAddress), port: codedPort, using: .udp)
}
func connect() {
connection.stateUpdateHandler = self.stateChanged(newState:)
connection.start(queue: .global())
}
func stateChanged(newState: NWConnection.State) {
print(#function)
switch (newState) {
case .ready:
print("State: Ready\n")
self.receiveUDP()
case .setup:
print("State: Setup\n")
case .cancelled:
print("State: Cancelled\n")
case .preparing:
print("State: Preparing\n")
default:
print("ERROR! State not defined!\n")
}
}
func sendUDP(_ content: String) {
let contentToSendUDP = content.data(using: String.Encoding.utf8)
self.connection.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
print("Data was sent to UDP")
} else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
}
})))
}
func receiveUDP() {
while self.connection.state == .ready {
self.connection.receiveMessage { (data, context, isComplete, error) in
if (isComplete) {
print("Receive is complete")
if (data != nil) {
let backToString = String(decoding: data!, as: UTF8.self)
print("Received message: \(backToString)")
} else {
print("Data == nil")
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment