Appearance
UDP Programming
TCP establishes a reliable connection, allowing both parties to send data as a stream. In contrast, UDP is a connectionless protocol.
When using UDP, there’s no need to establish a connection; you simply need to know the other party's IP address and port number to send data packets directly. However, there's no guarantee that the packets will arrive.
Although data transmission via UDP is unreliable, its advantages include faster speed compared to TCP. It is suitable for applications that do not require guaranteed delivery.
UDP Server
Let's look at how to transmit data using the UDP protocol. Similar to TCP, communication over UDP involves a client and a server. The server first needs to bind to a port:
python
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the port:
s.bind(('127.0.0.1', 9999))
When creating the socket, SOCK_DGRAM
specifies that this socket is for UDP. The binding of the port is the same as with TCP, but there’s no need to call the listen()
method. Instead, the server directly receives data from any client:
python
print('Bind UDP on 9999...')
while True:
# Receive data:
data, addr = s.recvfrom(1024)
print('Received from %s:%s.' % addr)
s.sendto(b'Hello, %s!' % data, addr)
The recvfrom()
method returns the data along with the client's address and port. After receiving the data, the server can directly use sendto()
to send data back to the client via UDP.
Note that we omit multithreading here because this example is quite simple.
UDP Client
When using UDP, the client first creates a UDP-based socket. There's no need to call connect()
; instead, it sends data to the server directly using sendto()
:
python
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Michael', b'Tracy', b'Sarah']:
# Send data:
s.sendto(data, ('127.0.0.1', 9999))
# Receive data:
print(s.recv(1024).decode('utf-8'))
s.close()
Receiving data from the server still uses the recv()
method.
To test, run the server and client in two separate command line windows, resulting in output like this:
┌────────────────────────────────────────────────────────┐
│Command Prompt - □ x │
├────────────────────────────────────────────────────────┤
│$ python udp_server.py │
│Bind UDP on 9999... │
│Received from 127.0.0.1:63823... │
│Received from 127.0.0.1:63823... │
│Received from 127.0.0.1:63823... │
│ ┌────────────────────────────────────────────────┴───────┐
│ │Command Prompt - □ x │
│ ├────────────────────────────────────────────────────────┤
│ │$ python udp_client.py │
└───────┤Hello, Michael! │
│Hello, Tracy! │
│Hello, Sarah! │
│$ │
│ │
│ │
└────────────────────────────────────────────────────────┘
Summary
The use of UDP is similar to TCP, but it doesn't require establishing a connection. Additionally, the server's binding of UDP ports and TCP ports does not conflict, meaning that UDP port 9999 can coexist with TCP port 9999.