TCP and UDP live in layer 4.
TCP pros and cons
Pros
- acknowledgment
- guaranteed delivery
- connection based
- congestion control
- ordered packets
Cons
- Larger packets
- More bandwidth since more headers.
- Slower (because of retransmission) than UDP
- Stateful (once connection is lost, cannot resume it).
- Server memory (DOS)
TCP code example
// server
const net = require('net');
const server = net.createServer((socket) => {
socket.write('Hello.');
socket.on('data', (data) => {
console.log(data.toString());
});
});
server.listen(8080);
// client using telnet, which can be installed by homebrew
telnet 127.0.0.1 8080
// client result
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello.
UDP (user datagram protocol) pros and cons
Cons
- Horizontal Scaling
- No acknowledgment
- No guaranteed delivery
- connectionless
- No congestion control
- No ordered packets
- Lack of security (No connection, I don’t know who you are). Many firewalls disable UDP for this reason
Pros
- Smaller packets
- Less bandwidth
- Faster than TCP
- Stateless
UDP code example
// server
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
socket.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
socket.bind(8081);
send to server using
netcat
(nc) echo "hi" | nc -w1 -u 127.0.0.1 8081
Many video streaming adopts UDP. It’s fast.
DNS needs to be stateless, so UDP