1
0

More than 3 years have passed since last update.

Python3: UDP を受信

Last updated at Posted at 2021-08-25

こちらの記事を参考にしました。
UDPでデータを受信する最も単純なPythonコード(Jupyter notebook版)

次のバージョンで確認しました。

$ python3 --version
Python 3.7.3

ポート 8092 の受信

receive.py
#! /usr/bin/python3
#
#   receive.py
#
#                           Aug/25/2021
#
import socket
import sys

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind(("0.0.0.0",8092))

sys.stderr.write("*** start ***\n")

while True:
    try:
        rcv_byte = bytes() #バイトデータ受信用変数
        rcv_byte, addr = udp.recvfrom(1024) #括弧内は最大バイト数設定
        msg = rcv_byte.decode() #バイトデータを文字列に変換
        print(len(msg))
        print(msg)
        if msg.strip() == 'close':
            udp.close()
            break
    except KeyboardInterrupt:
        udp.close()

ポート 8092 に udp で送信するスクリプト

echo 'Good Morning' | ncat -4 -u -w 1 localhost 8092

終了させるスクリプト

echo 'close' | ncat -4 -u -w 1 localhost 8092
1
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
1
0