LoginSignup
0
0

More than 1 year has passed since last update.

Python Socket通信

Posted at

概要

pythonで Socket通信に関して学んだので、その実際にSocket通信(TCP)するPG作ってみました。

前提

  • Python 3.9.7

目次

Ⅰ. Socket Server
Ⅱ. Socket Client

Ⅰ.Socket Server

元々、socket自体は入っているので、インストール不要。なので、そのまま、importを行う。

import socket

まず、Serverを作成していきます。

import socket

# with構文使用することで、close不要になるため使用します。
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  s.bind((socket.gethostname(), 50000))  # IPとポート指定
  s.listen(10)                           # サーバなので、Listen状態にします。10は、キューに貯める数。

  # 何度もレスポンスを返せるように、ここで無限ループにします。
  while True:
    conn, address = s.accept() # 接続受信
    print('Connection is established by {}'.format(address))
    
    # ここで、接続開きます。
    with conn:
      data = conn.recv(2048) # 格納できるバッファー指定 
      conn.sendall(data)     # 受け取ったデータをここで返します。

※ AF_INET:Ipv4
※ SOCK_STREAM:TCP通信

Ⅱ.Socket Client

次に、client作成していきます。

import socket

# with構文使用することで、close不要になるため使用します。
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  
  # サーバへ接続
  s.connect((socket.gethostname(), 50000))

  # データ送信 
  s.sendall(b'Connect to Socket Server')

  # レスポンスで受け取ったデータを取得して表示
  data = s.recv(2048)
  print(repr(data))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0