| 1 | = テスト用スクリプト = |
| 2 | |
| 3 | stream device の試験をするときに、切り分けるためにソフトウェアで tcp server があると便利。 |
| 4 | Echo Server のサンプルをベースにした書きなぐりのスクリプトですが、誰かの役に立つかもしれないので掲載しておく。 |
| 5 | |
| 6 | |
| 7 | コマンドや応答を適当に書き換えていただければ使えると思います。 |
| 8 | |
| 9 | |
| 10 | {{{ |
| 11 | import SocketServer |
| 12 | import string |
| 13 | import sys |
| 14 | import time |
| 15 | import signal |
| 16 | import random |
| 17 | |
| 18 | HOST = '' |
| 19 | PORT = 9999 |
| 20 | |
| 21 | class EchoHandler(SocketServer.BaseRequestHandler): |
| 22 | def handle(self): |
| 23 | print time.ctime(time.time()), " Connected from ", self.client_address |
| 24 | |
| 25 | flag = 1 |
| 26 | fid = self.request.makefile() |
| 27 | while flag: |
| 28 | receivedData = fid.readline() |
| 29 | if not receivedData: break |
| 30 | comd = string.strip(receivedData) |
| 31 | ret = string.upper(string.strip(comd)) |
| 32 | if ret=='QUIT': |
| 33 | flag = 0 |
| 34 | elif ret=='CURRENT?': |
| 35 | buf = self.creRetStr() + "\r\n" |
| 36 | self.request.send(buf) |
| 37 | elif ret=='*IDN?': |
| 38 | buf = "Simulator\r\n" |
| 39 | self.request.send(buf) |
| 40 | else: |
| 41 | ret = ret + '\r\n' |
| 42 | self.request.send(ret) |
| 43 | fid.close() |
| 44 | self.request.close() |
| 45 | print time.ctime(time.time()), " Disconnected (from ", self.client_address, ")" |
| 46 | |
| 47 | def creRetStr(self): |
| 48 | random.seed() |
| 49 | val = (random.random()-0.5)*1000 |
| 50 | #buf = "A=%8.4f, B=%8.4f, C=%8.4f"%(val,val,val2*2.345) |
| 51 | if val>0: |
| 52 | buf = "%8.4f"%val |
| 53 | else: |
| 54 | buf = "ERROR:%f"%val |
| 55 | |
| 56 | return buf |
| 57 | # end of class EchoHandler |
| 58 | |
| 59 | def signal_handler(signal, frame): |
| 60 | sys.exit(0) |
| 61 | |
| 62 | # __ main __ |
| 63 | if __name__ == '__main__': |
| 64 | signal.signal(signal.SIGINT, signal_handler) |
| 65 | SocketServer.ForkingTCPServer.allow_reuse_address = True |
| 66 | srv = SocketServer.ForkingTCPServer((HOST,PORT), EchoHandler) |
| 67 | print "StreamDevice Simulator started." |
| 68 | srv.serve_forever() |
| 69 | }}} |
| 70 | |