Whilst TCP is a protocol built for reliability, User Datagram Protocol (UDP) is minimalistic and more suited to use cases where speed is more important than consistency (for instance, gaming or media streaming).
Node supplies UDP via the dgram module.
Let's reimplement our recipe with UDP.
First, we'll rewrite client.js:
const dgram = require('dgram')
const socket = dgram.createSocket('udp4')
const name = process.argv[2] || 'Dave'
socket.bind(1400)
socket.send(name, 1339)
socket.on('message', (data) => {
console.log(data.toString())
})
Notice that we're no longer listening for a close event. This is because it's now pointless to do so because our server (as we'll see) is incapable of closing the client connection.
Let's implement the server.js file:
const dgram = require('dgram')
const socket = dgram.createSocket('udp4')
socket.bind(1339)
socket.on('message', (name) => {
socket.send(`Hi ${name}!`, 1400)
})
Now, the server looks much more like a client than a server.
This is because there's no real concept of server-client architecture with UDP--that's implemented by the TCP layer.
There are only sockets, which bind to a specific port and listen.
We cannot bind two processes to the same port, so, to get similar functionality we actually have to bind to two ports. There is a way to have multiple processes bind to the same port (using the reuseAddr option), but then we would have to deal with both processes receiving the same packets. Again, this is something TCP usually deals with.
Our client binds to port 1400, and sends a message to port 1399, whereas our server binds to port 1339 (so it can receive the client's message) but sends a message to port 1400 (which the client will receive).
Notice we use a send method instead of a write method as in the main recipe. The write method is part of the streams API; UDP sockets are not streams (the paradigm doesn't fit because they're not reliable nor persistent).
Likewise, we no longer listen for a data event, but a message event. Again, the data event belongs to the streams API, whereas message is part of the dgram module.
We'll notice that the server (like the client) no longer listens for a close event. This is because the sockets are bound to different ports so there's no way (without a higher level protocol such as TCP) of triggering a close from the other side.