I am trying to write a UDP client in Swift 5 which sends data to a UDP server which is running on a windows machine. The UDP Server is written in c#
The c# end does this:
IPAddress ipAddress = IPAddress.Parse("192.168.1.228);
IPEndPoint endPoint = new IPEndPoint(ipAddress, 10010);
udpClient = new UdpClient(endPoint);
udpClient.Connect("192.168.1.53, 4001);
udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
And my Swift client is this:
class MeetingMaker {
var connection: NWConnection?
var host: NWEndpoint.Host = "192.168.1.228"
var port: NWEndpoint.Port = 10010
var m2h: MotionToHost = MotionToHost()
var timer = Timer()
func send(_ payload: Data) {
connection!.send(content: payload, completion: .contentProcessed({ sendError in
if let error = sendError {
print("Unable to process and send the data: \(error)")
} else {
print("Data has been sent")
}
}))
}
func startSendingUpdates() {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
self.sendTick()
}
}
func sendTick() {
if connection?.state == .ready {
//print("MB SEND")
send(m2h.asData())
}
}
func connect() {
connection = NWConnection(host: host, port: port, using: .udp)
connection!.stateUpdateHandler = { (newState) in
switch (newState) {
case .preparing:
NSLog("MB: Entered state: preparing")
case .ready:
NSLog("MB: Entered state: ready")
case .setup:
NSLog("MB: Entered state: setup")
case .cancelled:
NSLog("MB: Entered state: cancelled")
case .waiting:
NSLog("MB: Entered state: waiting")
case .failed:
NSLog("MB: Entered state: failed")
default:
NSLog("MB: Entered an unknown state")
}
}
connection!.viabilityUpdateHandler = { (isViable) in
if (isViable) {
NSLog("MB: Connection is viable")
} else {
NSLog("MB: Connection is not viable")
}
}
connection!.betterPathUpdateHandler = { (betterPathAvailable) in
if (betterPathAvailable) {
NSLog("MB: A better path is availble")
} else {
NSLog("MB: No better path is available")
}
}
connection!.start(queue: .global())
}
}
And elsewhere :
meetingMaker.Connect()
And
meetingMaker.StartSendingUpdates()
The issue is that the UDP Server on windows never receives the packets. I think it expects them to come from source-port 4001? I cannot find how to bind my Swift UDP CLient to send from a specified local port?
(The IP addresses are fixed and correct).
Is it possible to use Swift to send UDP packets from a specific local port, to the specified destination port? Or is the issue elsewhere?
I might be completely wrong here, but it looks like you can do this line differently
connection = NWConnection(host: host, port: port, using: .udp)
the last parameter doesn't need to be fixed as .udp, the default udp parameters. You can make new NWParameters and alter the value of requiredLocalEndpoint.
hth, and Happy New Year