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

소켓 API 소개

소켓 유형, 주소 및 일반적인 API 호출을 포함한 소켓 프로그래밍의 핵심 개념을 살펴봅니다.

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

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

What are Network Sockets?

Welcome to socket programming! A socket is a crucial concept in network communication. Think of it as one endpoint of a two-way communication link between two programs running on the network.

It's like a phone jack on a wall. You plug a phone into it to connect to the phone network. Similarly, programs use sockets to connect and talk over a computer network.

Python's Socket Module

Python makes socket programming accessible through its built-in socket module. This module provides all the necessary functions and classes to create and manage sockets.

You'll typically import it at the beginning of your script. Let's see how to get started:

import socket

# Now you can use socket functions!

Socket Address Families

Before creating a socket, we need to specify its address family. This determines the type of addresses the socket can work with.

  • socket.AF_INET: Used for IPv4 addresses (e.g., 192.168.1.1). This is the most common.
  • socket.AF_INET6: Used for IPv6 addresses.
  • socket.AF_UNIX: Used for communication between processes on the same machine.

We'll primarily use AF_INET for standard internet communication.

Socket Types: Stream vs. Datagram

Next, we choose the socket type, which defines the communication style.

  • socket.SOCK_STREAM: This type uses TCP (Transmission Control Protocol). It's reliable, ordered, and connection-oriented, like a phone call. Data arrives exactly as sent.
  • socket.SOCK_DGRAM: This type uses UDP (User Datagram Protocol). It's connectionless and less reliable, like sending postcards. Data might arrive out of order or not at all.

Most common applications, especially web browsing, use SOCK_STREAM.

Creating Your First Socket

Now let's put it together and create a basic socket object. We'll specify the address family (IPv4) and the socket type (TCP stream).

This line creates an inactive socket that's ready to be configured for either client or server roles.

import socket

# Create a TCP/IP socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print(f"Socket created: {my_socket}")
# Don't forget to close sockets when done!
my_socket.close()

Binding a Socket (Server Side)

For a server, the socket needs an address to listen on. This is called binding. You assign an IP address and a port number to your socket.

Clients will use this address and port to connect to your server. A port is a number that identifies a specific application or service on a host.

import socket

HOST = '127.0.0.1'  # Localhost
PORT = 65432        # Port to listen on (> 1023 for non-privileged)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    print(f"Socket bound to {HOST}:{PORT}")
    # The socket is now bound, but not yet listening or accepting.

Listening for Connections

After binding, a server socket must listen for incoming client connections. The listen() method puts the socket into server mode.

The argument to listen() is the backlog, which is the maximum number of unaccepted connections that the system will allow before refusing new connections.

import socket

HOST = '127.0.0.1'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1) # Allow 1 pending connection
    print(f"Server listening on {HOST}:{PORT}")
    # Now the server is ready to accept a connection.

Accepting a Connection

When a client tries to connect, the server uses the accept() method. This method blocks (waits) until a client connects.

It then returns a new socket object (conn) representing the connection to the client, and the client's address (addr). All communication with the client happens via this new socket.

import socket

HOST = '127.0.0.1'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    print("Waiting for a client connection...")
    # This part would typically be in a loop in a real server
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        # Now 'conn' can be used to send/receive data to/from the client.

Connecting to a Server (Client Side)

A client socket doesn't bind; instead, it uses the connect() method to establish a connection with a server that is listening on a specific IP address and port.

Once connected, the client can immediately start sending and receiving data. Data is always exchanged as bytes.

import socket

HOST = '127.0.0.1'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    try:
        s.connect((HOST, PORT))
        print(f"Connected to server at {HOST}:{PORT}")
        s.sendall(b'Hello from client!')
        data = s.recv(1024) # Receive up to 1024 bytes
        print(f"Received: {data.decode()}")
    except ConnectionRefusedError:
        print("Error: Server not running or not listening.")

Sending and Receiving Data

Once a connection is established, data can be exchanged using sendall() and recv().

  • socket.sendall(data): Sends all of the byte-like data to the connected socket. It keeps sending until all data is sent or an error occurs.
  • socket.recv(bufsize): Receives data from the socket. bufsize is the maximum number of bytes to be received at once. It returns an empty bytes object (b'') when the connection is closed.

Socket API Quick Check

Which of the following statements about Python's socket module and socket types is TRUE?

Recap: Intro to Sockets

Great job! In this lesson, you've taken your first steps into socket programming with Python. You learned:

  • What a network socket is and its role in communication.
  • About Python's socket module.
  • The difference between address families (AF_INET, AF_INET6) and socket types (SOCK_STREAM for TCP, SOCK_DGRAM for UDP).
  • The basic API calls: socket() for creation, bind() and listen() for servers, and connect() for clients.
  • How accept() handles incoming connections and how sendall()/recv() work.

Next, we'll dive deeper into building full TCP client-server applications!

자주 묻는 질문

“소켓 API 소개” 강의는 무료인가요?

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

“소켓 API 소개”에서 뭘 배우나요?

소켓 유형, 주소 및 일반적인 API 호출을 포함한 소켓 프로그래밍의 핵심 개념을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Linux Networking & TCP/IP for Developers을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“소켓 API 소개” 강의는 얼마나 걸리나요?

대부분의 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(으)로 돌아가기