LoginSignup
27
22

More than 1 year has passed since last update.

PythonによるUDP通信

Last updated at Posted at 2018-12-14

はじめに

よくUDP通信をするので、まとめてみました。内容はコメント通り。

送信

from socket import socket, AF_INET, SOCK_DGRAM

HOST = ''
PORT = 5000
ADDRESS = "127.0.0.1" # 自分に送信

s = socket(AF_INET, SOCK_DGRAM)
# ブロードキャストする場合は、ADDRESSを
# ブロードキャスト用に設定して、以下のコメントを外す
# s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

while True:
    msg = input("> ")
    # 送信
    s.sendto(msg.encode(), (ADDRESS, PORT))

s.close()

受信

from socket import socket, AF_INET, SOCK_DGRAM

HOST = ''   
PORT = 5000

# ソケットを用意
s = socket(AF_INET, SOCK_DGRAM)
# バインドしておく
s.bind((HOST, PORT))

while True:
    # 受信
    msg, address = s.recvfrom(8192)
    print(f"message: {msg}\nfrom: {address}")

# ソケットを閉じておく
s.close()

参考

27
22
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
27
22