0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python2 > UDP > コマンド応答処理 > udpResponder_171222 > v0.1

Last updated at Posted at 2017-12-22
動作環境
CentOS 6.8 (64bit)
   Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Ubuntu 16.04 LTS
   Python 2.7.11+

C++ BuilderのUDP通信プログラムのデバッグとして、CentOS6.8で動作するPythonスクリプトを実装した。

処理

  • UDPコマンドを受信する
  • コマンドに対応する応答を返信する

code v0.1

udpResponder_171222.py
import socket as skt
import json

'''
v0.1 Dec. 22, 2017
  - add [myDict] dictionary
  - add udpResponder()
'''

# on Python 2.6.6

myDict = {
    "hello": "hi",
    "serious": "I'm serious",
}

RECV_TIMEOUT_MSEC = 300


def udpResponder(port_in):
    inst = skt.socket(skt.AF_INET, skt.SOCK_DGRAM)
    inst.bind(('', port_in))
    inst.setblocking(0)
    while True:
        try:
            data, adr = inst.recvfrom(RECV_TIMEOUT_MSEC)
        except skt.error:
            pass
        else:
            print("from:", adr)
            print("rcvd:", data)
            data = data.rstrip('\n')
            data = data.rstrip('\r')
            data = data.rstrip('\n')
            #
            rep = myDict.get(data)
            if rep is None:
                continue
            print("ret:", rep)
            inst.sendto(rep, adr)

udpResponder(7000)

  • コマンド終端は<CR><LF><CR><LF><LF><CR>に対応
  • コマンド応答のテーブルはmyDictに記載している
    • 別ファイルにしても良い
    • csvやJSONにするなど

実行例

UDPコマンド送信側はNonSoftさんのUDP/IPテストツールを使わせていただきました。

いつも役立っています。

$ python udpResponder_171222.py 
('from:', ('192.168.XXX.141', 9000))
('rcvd:', 'hello\r\n')
('ret:', 'hi')
('from:', ('192.168.XXX.141', 9000))
('rcvd:', 'serious\r\n')
('ret:', "I'm serious")
('from:', ('192.168.XXX.141', 9000))
('rcvd:', 'hi\r\n')
UDP/IPテストツール側
接続                (9000 )
送-> 192.168.XXX.140 (7000 )hello<CR><LF>
->受 192.168.XXX.140 (7000 )hi
送-> 192.168.XXX.140 (7000 )serious<CR><LF>
->受 192.168.XXX.140 (7000 )I'm serious
送-> 192.168.XXX.140 (7000 )hi<CR><LF>
切断                (9000 )

関連

Python 3

Visual Studio 2017 communityにPython 3環境を構築し、上記のコードを実行した。
data = data.rstrip('\n')の部分で以下のエラーになった。

TypeError: a bytes-like object is required, not 'str'

Ubuntu 16.04 LTS + Python 3.5.2でも同じエラーになった。
以下のような処理が必要になる。

data = data.decode("utf-8")
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?