← All writing
HackerNoonMarch 2025

Building a UDP Server & Client in Swift

Most iOS networking lives at the application layer, where URLSession is the right answer. Below that, the Network framework offers direct control over TCP and UDP, which is what you need for latency-sensitive or non-HTTP protocols.

The piece covers why working at the transport layer is sometimes the correct choice, what UDP gives up in exchange for what it gains, and then builds both halves — a UDPServer and a UDPClient — as code you can run rather than as a description of an API.

The case for skipping TCP's handshake rests on a real example: testing a connected vehicle, at Arrival, where commands from the mobile app had to reach the car fast enough that a tester could steer it almost like a radio-controlled toy. That anecdote is what motivates the trade the rest of the piece works through — accepting that a dropped packet is simply gone in return for not paying a connection-setup cost on every message.

Both halves are built the same way: a package is scaffolded, the server or client type is written behind a small protocol so the Network.framework details stay out of its public surface, and the result is exercised from the command line rather than left as an untested listing.

What's inside

  • The case for dropping to the transport layer at all: URLSession's overhead is fine for ordinary requests but wrong for VoIP, real-time games, streaming, or IoT devices and real-time protocols that need low latency and fine control over packets.
  • TCP's three-way handshake versus UDP's connectionless send, laid out as the actual mechanical reason one protocol adds latency the other doesn't, rather than as a naming distinction.
  • A first-hand account of using UDP to send commands to a test vehicle, cited as the reason the piece treats occasional packet loss as an acceptable cost against near-instant delivery.
  • The UDPServer build: scaffolding a Swift package, wrapping NWListener behind a small server protocol, and wiring it into a runnable command-line target.
  • The UDPClient build, mirrored against the server: an NWConnection-backed type behind its own protocol, wired into a runnable command-line entry point.
  • What the demo leaves for a real deployment to add: handling more than one client at a time, sturdier failure handling, and extra tuning of the connection for more demanding real-time use.
The takeaway

The argument is narrow and practical: URLSession covers almost all iOS networking, but for the remaining slice — real-time, latency-sensitive, non-HTTP traffic — Network.framework's UDP support is a deliberate trade of reliability for speed, demonstrated with a server and client that actually run rather than described in the abstract.

Get the full NWListener/NWConnection server-and-client code on HackerNoon ↗