Hi,
I am trying to build and run a sample client server using NWFramework for UDP.
I have been successfully able to send and receive the packet using NWConnection and NWListner but the issue I am facing is regarding the member of NWListner which is newConnectionHandler which is used to handle receives inbound connections.
But UDP is connectionless protocol and I don't want my server to receive inbound connections as in UDP the server treat each packet as independent packet without maintaining any connection or connection info of client.
Please Find the refernce to the sample code below.
Can it be done without newConnectionHandler or is there any way to do communication on all the Apple Family without using BSD sockets as BSD sockets are not suported on watchOS
import Foundation
import Network
class Server {
private var listener: NWListener?
private let dispatchGroup = DispatchGroup()
private var receivedPackets: [String] = []
func startListening() {
do {
let parameters = NWParameters.udp
let port = NWEndpoint.Port(integerLiteral: 12345)
listener = try NWListener(using: parameters, on: port)
listener?.stateUpdateHandler = { state in
switch state {
case .ready:
print("Server is ready to accept connections.")
case .failed(let error):
print("Server failure, error: \(error.localizedDescription)")
default:
break
}
}
listener?.newConnectionHandler = { [weak self] newConnection in
self?.handleNewConnection(newConnection)
}
listener?.start(queue: .main)
//RunLoop.main.run()
dispatchGroup.wait()
} catch {
print("Failed to start the server, error: \(error.localizedDescription)")
}
}
private func handleNewConnection(_ connection: NWConnection) {
connection.stateUpdateHandler = { state in
switch state {
case .ready:
print("Client connected.")
self.receiveData(on: connection)
case .failed(let error):
print("Connection failure, error: \(error.localizedDescription)")
default:
break
}
}
connection.start(queue: .main)
}
private func receiveData(on connection: NWConnection) {
connection.receiveMessage { (data, context, isComplete, error) in
if let data = data, !data.isEmpty {
let message = String(data: data, encoding: .utf8)
print("Received message: \(message ?? "")")
// Process the received message
// Process the received message
if let message = message {
self.receivedPackets.append(message)
}
if self.receivedPackets.count == 50 {
// All expected packets received
print("Received all packets:")
for packet in self.receivedPackets {
print(packet)
}
// Close the connection after receiving all packets
// connection.cancel()
} else {
// Continue receiving more packets
self.receiveData(on: connection)
}
}
if let error = error {
print("Failed to receive data, error: \(error.localizedDescription)")
}
}
}