0Pricing
Linux Networking & TCP/IP for Developers · レッスン

TCPクライアント・サーバーソケット

Pythonで基本的なTCPクライアントとサーバーのアプリケーションを構築し、信頼性のあるコネクション指向通信を実装します。

「TCPクライアント・サーバーソケット」はCoddyKit上の無料Linux Networking & TCP/IP for Developersレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはLinux Networking & TCP/IP for Developers学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Linux Networking & TCP/IP for Developersコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

TCP Sockets: Connection First

Welcome to building network applications with Python! This lesson focuses on TCP (Transmission Control Protocol) sockets, which are the backbone of reliable internet communication.

Unlike UDP, TCP is a connection-oriented protocol. This means a direct, stable link is established between two applications before any data is sent.

Why TCP is Reliable

TCP ensures your data arrives correctly and in order. It handles:

  • Guaranteed Delivery: Data segments are retransmitted if lost.
  • Ordered Data: Data arrives in the order it was sent.
  • Error Checking: Data integrity is verified.
  • Flow Control: Prevents a fast sender from overwhelming a slow receiver.

This makes TCP ideal for web browsing, email, and file transfers.

TCP Server: The Listener

A TCP server's role is to listen for incoming connections from clients. Here's the typical workflow for a server:

  1. Create a socket.
  2. Bind the socket to an IP address and port.
  3. Listen for client connections.
  4. Accept an incoming connection.
  5. Communicate (send/receive data).
  6. Close the sockets.

Creating a Python TCP Socket

In Python, we use the built-in socket module. To create a TCP socket, we specify socket.AF_INET for IPv4 addressing and socket.SOCK_STREAM for TCP.

Try running this basic example:

import socket

def main():
    # Create a TCP/IP socket
    # AF_INET for IPv4, SOCK_STREAM for TCP
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("TCP socket created successfully!")
    tcp_socket.close()
    print("Socket closed.")

if __name__ == "__main__":
    main()

Server: Bind to Address & Port

After creating the socket, the server needs to bind it to a specific IP address and port number. This tells the operating system where the server will listen for connections.

.bind((HOST, PORT)) associates the socket. .listen(backlog) prepares it to accept connections, with backlog being the max queued connections.

import socket

def main():
    HOST = '127.0.0.1'  # Localhost
    PORT = 65432        # Port to listen on (non-privileged)

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        server_socket.bind((HOST, PORT))
        server_socket.listen(1) # Allow 1 pending connection
        print(f"Server listening on {HOST}:{PORT}")
    except Exception as e:
        print(f"Error binding or listening: {e}")
    finally:
        server_socket.close()
        print("Server socket closed.")

if __name__ == "__main__":
    main()

Server: Accepting a Client

The .accept() method is crucial for a server. It blocks execution until a client tries to connect. When a connection is made, it returns two values:

  • A new socket object (conn) for communicating with that specific client.
  • The client's address (addr), a (host, port) tuple.
import socket

def main():
    HOST = '127.0.0.1'
    PORT = 65432

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen(1)
    print(f"Server waiting for connection on {HOST}:{PORT}...")

    # This will block until a client connects
    conn, addr = server_socket.accept()
    with conn: # Use 'with' for auto-closing the client socket
        print(f"Connected by client from {addr}")
        # In a real app, send/recv would happen here
        conn.sendall(b"Hello from server!") # Send some bytes
        print("Sent greeting to client.")
    server_socket.close()
    print("Server socket closed.")

if __name__ == "__main__":
    main()

TCP Client: Initiating Connection

A TCP client's role is to initiate a connection to a server. Here's its typical workflow:

  1. Create a socket.
  2. Connect to the server's IP address and port.
  3. Communicate (send/receive data).
  4. Close the socket.

Client: Connecting to Server

The client uses the .connect((HOST, PORT)) method to establish a connection with the server. If successful, a virtual circuit is created. If the server isn't listening, you'll get a ConnectionRefusedError.

Run this. If no server is running, it will show an error:

import socket

def main():
    HOST = '127.0.0.1'  # Server's IP address
    PORT = 65432        # Server's port

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        print(f"Attempting to connect to server at {HOST}:{PORT}...")
        client_socket.connect((HOST, PORT))
        print("Successfully connected to the server!")
    except ConnectionRefusedError:
        print("Connection refused. Is the server running?")
    except Exception as e:
        print(f"Client connection error: {e}")
    finally:
        client_socket.close()
        print("Client socket closed.")

if __name__ == "__main__":
    main()

Sending & Receiving Data

Once connected, both client and server can send and receive data. Remember that network data is transmitted as bytes, so you'll often need to .encode() strings before sending and .decode() received bytes back into strings.

  • .sendall(data): Sends all data reliably.
  • .recv(buffer_size): Receives up to buffer_size bytes.
import socket

def main():
    HOST = '127.0.0.1'
    PORT = 65432

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect((HOST, PORT))
        message = "Hello from the client!"
        client_socket.sendall(message.encode('utf-8'))
        print(f"Client sent: '{message}'")

        data = client_socket.recv(1024) # Receive up to 1024 bytes
        if data:
            print(f"Client received: '{data.decode('utf-8')}'")
        else:
            print("Client received no data (server might have closed).")
    except ConnectionRefusedError:
        print("Connection refused. Please run the server example first!")
    except Exception as e:
        print(f"Client communication error: {e}")
    finally:
        client_socket.close()
        print("Client socket closed.")

if __name__ == "__main__":
    main()

TCP Communication Flow

Consider the typical steps for a Python TCP server to establish a connection and an echo client to communicate.

Recap: TCP Client-Server Sockets

Great job! You've learned the fundamentals of TCP client-server communication in Python:

  • TCP provides reliable, connection-oriented communication.
  • Servers bind to an address, listen for connections, and accept clients.
  • Clients connect to a server's address.
  • Both use .sendall() to send and .recv() to receive bytes.

These concepts are crucial for building robust networked applications!

よくある質問

「TCPクライアント・サーバーソケット」レッスンは無料ですか?

はい。「TCPクライアント・サーバーソケット」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Linux Networking & TCP/IP for Developersコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Linux Networking & TCP/IP for Developersコースには全4レッスンが含まれています。

「TCPクライアント・サーバーソケット」で何を学びますか?

Pythonで基本的なTCPクライアントとサーバーのアプリケーションを構築し、信頼性のあるコネクション指向通信を実装します。 ブラウザで直接実行するハンズオンコードでLinux Networking & TCP/IP for Developersを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Linux Networking & TCP/IP for Developersを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのLinux Networking & TCP/IP for Developersは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「TCPクライアント・サーバーソケット」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このLinux Networking & TCP/IP for Developersレッスンでコードを書いて実行できますか?

はい。すべてのLinux Networking & TCP/IP for Developersレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Socket API入門
  2. TCPクライアント・サーバーソケット
  3. UDPクライアント・サーバーソケット
  4. ノンブロッキングソケットとselect()
← Linux Networking & TCP/IP for Developersに戻る