Python ソケットと基本的な通信の理解
ソケットとは何か、そして Python でどのように機能するかを理解することから始めましょう。
ソケットとは?
ソケットは、ネットワーク経由でデータを送受信するためのエンドポイントです。ネットワーク通信が流れる仮想的な接続ポイントと考えてください。Python の組み込み socket モジュールは、ネットワーク通信のためにソケットを作成、設定、使用するためのツールを提供します。
基本的なソケット通信の流れ
ソケット通信は通常、次の手順に従います。
- ソケットオブジェクトを作成する
- ソケットをアドレスにバインドする(サーバーの場合)
- 着信接続をリッスンする(サーバーの場合)
- 接続を受け入れる(サーバーの場合)またはサーバーに接続する(クライアントの場合)
- データを送受信する
- 完了したらソケットを閉じる
これらの概念をより良く理解するために、最初のシンプルなソケットプログラムを作成しましょう。
最初のソケットサーバーの作成
まず、接続をリッスンし、受信したデータをエコーバックする基本的なソケットサーバーを作成しましょう。
WebIDE を開き、/home/labex/project ディレクトリに server.py という名前の新しいファイルを作成し、次の内容を記述します。
import socket
## Define server address and port
HOST = '127.0.0.1' ## Standard loopback interface address (localhost)
PORT = 65432 ## Port to listen on (non-privileged ports are > 1023)
## Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket created successfully")
## Bind the socket to the specified address and port
server_socket.bind((HOST, PORT))
print(f"Socket bound to {HOST}:{PORT}")
## Listen for incoming connections
server_socket.listen(1)
print(f"Socket is listening for connections")
## Accept a connection
print(f"Waiting for a connection...")
connection, client_address = server_socket.accept()
print(f"Connected to client: {client_address}")
## Receive and echo data
try:
while True:
## Receive data from the client
data = connection.recv(1024)
if not data:
## If no data is received, the client has disconnected
print(f"Client disconnected")
break
print(f"Received: {data.decode('utf-8')}")
## Echo the data back to the client
connection.sendall(data)
print(f"Sent: {data.decode('utf-8')}")
finally:
## Clean up the connection
connection.close()
server_socket.close()
print(f"Socket closed")
最初のソケットクライアントの作成
次に、サーバーに接続するクライアントを作成しましょう。同じディレクトリに client.py という名前の新しいファイルを作成し、次の内容を記述します。
import socket
## Define server address and port
HOST = '127.0.0.1' ## The server's hostname or IP address
PORT = 65432 ## The port used by the server
## Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket created successfully")
## Connect to the server
client_socket.connect((HOST, PORT))
print(f"Connected to server at {HOST}:{PORT}")
## Send and receive data
try:
## Send data to the server
message = "Hello, Server!"
client_socket.sendall(message.encode('utf-8'))
print(f"Sent: {message}")
## Receive data from the server
data = client_socket.recv(1024)
print(f"Received: {data.decode('utf-8')}")
finally:
## Clean up the connection
client_socket.close()
print(f"Socket closed")
ソケットプログラムのテスト
それでは、ソケットプログラムをテストしましょう。LabEx VM で 2 つのターミナルウィンドウを開きます。
最初のターミナルで、サーバーを実行します。
cd ~/project
python3 server.py
次のような出力が表示されるはずです。
Socket created successfully
Socket bound to 127.0.0.1:65432
Socket is listening for connections
Waiting for a connection...
サーバーを実行したままにしておき、2 番目のターミナルを開いてクライアントを実行します。
cd ~/project
python3 client.py
次のような出力が表示されるはずです。
Socket created successfully
Connected to server at 127.0.0.1:65432
Sent: Hello, Server!
Received: Hello, Server!
Socket closed
そして、サーバーのターミナルには、次のように表示されるはずです。
Connected to client: ('127.0.0.1', XXXXX)
Received: Hello, Server!
Sent: Hello, Server!
Client disconnected
Socket closed
おめでとうございます!Python で最初のソケットベースのクライアントサーバーアプリケーションを作成し、テストしました。これは、ソケット通信の仕組みと、次のステップでエラー処理を実装する方法を理解するための基礎となります。