2018年6月6日水曜日

開発環境

入門 Python 3 (Bill Lubanovic (著)、斎藤 康毅 (監修)、長尾 高弘 (翻訳)、オライリージャパン)の11章(並行処理とネットワーク)、11.3(復習問題)2.を取り組んでみる。

コード(Emacs)

Python 3

server2.py

#!/usr/bin/env python3
import datetime
import zmq

f = open('server2.txt', 'w')

print('11-2', file=f)
host = '127.0.0.1'
port = 6789
context = zmq.Context()
server = context.socket(zmq.REP)
server.bind(f'tcp://{host}:{port}')
while True:
    request = server.recv_string()
    print(request, file=f)
    if request == 'time':
        s = datetime.datetime.now().isoformat()
    else:
        s = 'xxxxx'
    server.send_string(s)

server.close()
f.close()

client2.py

#!/usr/bin/env python3
import datetime
import zmq
import time

print('11-2')

host = '127.0.0.1'
port = 6789
context = zmq.Context()
client = context.socket(zmq.REQ)
client.connect(f'tcp://{host}:{port}')

for i in range(10):
    if i % 2 == 0:
        client.send_string('time')
    else:
        client.send_string('TIME')
    s = client.recv_string()
    print(s)
    time.sleep(5)

client.close()

入出力結果(Terminal, Jupyter(IPython))

$ ./server2.py &
[1] 63217
$ ./client2.py
11-2
2018-06-06T19:34:26.519351
xxxxx
2018-06-06T19:34:36.528852
xxxxx
2018-06-06T19:34:46.536524
xxxxx
2018-06-06T19:34:56.541838
xxxxx
2018-06-06T19:35:06.550626
xxxxx
$ fg
./server2.py
  C-c C-cTraceback (most recent call last):
  File "./server2.py", line 14, in <module>
    request = server.recv_string()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/zmq/sugar/socket.py", line 583, in recv_string
    msg = self.recv(flags=flags)
  File "zmq/backend/cython/socket.pyx", line 790, in zmq.backend.cython.socket.Socket.recv
  File "zmq/backend/cython/socket.pyx", line 826, in zmq.backend.cython.socket.Socket.recv
  File "zmq/backend/cython/socket.pyx", line 188, in zmq.backend.cython.socket._recv_copy
  File "zmq/backend/cython/checkrc.pxd", line 12, in zmq.backend.cython.checkrc._check_rc
KeyboardInterrupt
$ cat server2.txt 
11-2
time
TIME
time
TIME
time
TIME
time
TIME
time
TIME
$ 

0 コメント:

コメントを投稿

関連コンテンツ