0Pricing
Linux Networking & TCP/IP for Developers · 강의

UDP 클라이언트-서버 소켓

신뢰성보다 속도가 중요한 애플리케이션을 위해 UDP 소켓으로 비연결형 데이터그램 기반 통신을 개발합니다.

UDP 클라이언트-서버 소켓은(는) CoddyKit의 무료 Linux Networking & TCP/IP for Developers 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Linux Networking & TCP/IP for Developers 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Linux Networking & TCP/IP for Developers 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is UDP?

Welcome to UDP! While TCP focused on reliable, connection-oriented communication, UDP (User Datagram Protocol) offers a different approach: connectionless and unreliable.

Think of UDP like sending a postcard. You write the message and send it, but you don't know if it arrived, or in what order, or if it got lost. It's fast, but there's no guarantee.

UDP vs. TCP: Key Differences

Understanding when to use UDP means knowing its core differences from TCP:

  • Connectionless: No handshake needed before sending data.
  • Unreliable: No guaranteed delivery, ordering, or duplicate protection.
  • Faster: Less overhead due to no connection setup or reliability checks.
  • Datagrams: Data is sent in independent packets called datagrams.

UDP is perfect for applications where speed is more critical than guaranteed delivery.

When to Use UDP

UDP shines in scenarios where some data loss is acceptable, or where applications handle reliability themselves. Common uses include:

  • Online Gaming: Speed is crucial for real-time action.
  • Voice/Video Streaming: Small delays are better than retransmissions.
  • DNS (Domain Name System): Quick lookups are prioritized.
  • SNMP (Simple Network Management Protocol): Monitoring network devices.

These applications prioritize low latency over absolute data integrity.

The Python `socket` Module for UDP

Python's socket module is your toolkit for network programming, including UDP. To create a UDP socket, you specify the address family and socket type.

  • socket.AF_INET: For IPv4 addresses.
  • socket.SOCK_DGRAM: Specifies a UDP socket (datagram socket).

Let's see how to create one.

Creating a UDP Socket

Here's how to create a basic UDP socket. Notice it's very similar to TCP, but with SOCK_DGRAM.

Run this code to see a UDP socket being initialized and then closed.

import socket

def main():
    # AF_INET for IPv4, SOCK_DGRAM for UDP
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    print("UDP socket created successfully!")
    udp_socket.close()
    print("Socket closed.")

if __name__ == "__main__":
    main()

UDP Server: Binding to an Address

A UDP server needs to bind() to a specific IP address and port to listen for incoming datagrams. This tells the operating system where the server expects to receive data.

Unlike TCP, there's no listen() or accept() for UDP as it's connectionless. The server just waits to receive.

import socket

HOST = '127.0.0.1' # Localhost
PORT = 12345       # Port to listen on

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind((HOST, PORT))
    print(f"UDP server bound to {HOST}:{PORT}")
    udp_socket.close()

if __name__ == "__main__":
    main()

UDP Server: Receiving Data

The recvfrom() method is used by a UDP server to receive data. It returns both the data and the address of the sender.

The server below will wait for one message, print it, and then close. Try running it and then run the client code in the next scene!

import socket

HOST = '127.0.0.1'
PORT = 12345

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind((HOST, PORT))
    print(f"UDP server listening on {HOST}:{PORT}")

    print("Waiting for message...")
    data, addr = udp_socket.recvfrom(1024) # Buffer size 1024 bytes
    print(f"Received '{data.decode()}' from {addr}")
    udp_socket.close()

if __name__ == "__main__":
    main()

UDP Client: Sending Data

A UDP client uses the sendto() method to send data. It takes the data (as bytes) and the destination address (IP and port) as arguments.

The client doesn't need to bind to a specific port unless it expects to receive a reply on that port. An ephemeral port is assigned automatically.

Run this client after starting the server from the previous scene!

import socket

SERVER_HOST = '127.0.0.1'
SERVER_PORT = 12345

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    message = "Hello UDP Server!"
    udp_socket.sendto(message.encode(), (SERVER_HOST, SERVER_PORT))
    print(f"Sent '{message}' to {SERVER_HOST}:{SERVER_PORT}")
    udp_socket.close()

if __name__ == "__main__":
    main()

Full UDP Echo Server & Client

Let's create a simple UDP echo server that receives a message and sends it back to the client, and a client that sends a message and waits for the echo.

First, run the server. Then, run the client in a separate terminal or execution environment.

import socket

# --- UDP Echo Server ---
HOST = '127.0.0.1'
PORT = 12345

def run_server():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind((HOST, PORT))
    print(f"Server listening on {HOST}:{PORT}")

    try:
        while True:
            data, addr = udp_socket.recvfrom(1024)
            print(f"Received '{data.decode()}' from {addr}")
            # Echo back to the client
            udp_socket.sendto(b"Echo: " + data, addr)
            print(f"Echoed back to {addr}")
    except KeyboardInterrupt:
        print("Server shutting down.")
    finally:
        udp_socket.close()

if __name__ == "__main__":
    run_server()

Full UDP Echo Client

Now, run this client code. It will send a message to the running server and then wait to receive the echoed response.

This demonstrates a complete, simple UDP communication loop.

import socket

# --- UDP Echo Client ---
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 12345

def run_client():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    message = "Hello from UDP Client!"
    
    udp_socket.sendto(message.encode(), (SERVER_HOST, SERVER_PORT))
    print(f"Sent '{message}' to {SERVER_HOST}:{SERVER_PORT}")

    print("Waiting for echo...")
    data, addr = udp_socket.recvfrom(1024)
    print(f"Received echo '{data.decode()}' from {addr}")
    udp_socket.close()

if __name__ == "__main__":
    run_client()

UDP Client-Server Check

Which of the following statements about UDP sockets is TRUE?

Recap: UDP Sockets

In this lesson, you've explored the world of UDP sockets, understanding their fundamental differences from TCP.

  • UDP is connectionless and unreliable, prioritizing speed.
  • It uses datagrams for communication.
  • Python's socket module with SOCK_DGRAM creates UDP sockets.
  • Servers use bind() and recvfrom().
  • Clients use sendto().

Now you can choose the right protocol for your application's needs!

자주 묻는 질문

“UDP 클라이언트-서버 소켓” 강의는 무료인가요?

네 — “UDP 클라이언트-서버 소켓” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Linux Networking & TCP/IP for Developers 강의 전체를 잠금 해제할 수 있습니다. Linux Networking & TCP/IP for Developers 강의에는 총 4개의 강의가 포함되어 있습니다.

“UDP 클라이언트-서버 소켓”에서 뭘 배우나요?

신뢰성보다 속도가 중요한 애플리케이션을 위해 UDP 소켓으로 비연결형 데이터그램 기반 통신을 개발합니다. 브라우저에서 직접 실행하는 실습 코드로 Linux Networking & TCP/IP for Developers을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Linux Networking & TCP/IP for Developers을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Linux Networking & TCP/IP for Developers은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“UDP 클라이언트-서버 소켓” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Linux Networking & TCP/IP for Developers 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Linux Networking & TCP/IP for Developers 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 소켓 API 소개
  2. TCP 클라이언트-서버 소켓
  3. UDP 클라이언트-서버 소켓
  4. 비차단 소켓 및 select()
← Linux Networking & TCP/IP for Developers(으)로 돌아가기