2017年1月20日金曜日

開発環境

Introducing Python(Bill Lubanovic (著)、O'Reilly Media)のChapter 11(Concurrency and Networks)、Things to Do 11.2.を解いてみる。

Things to Do 11.2.

コード

server

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import datetime
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
server = ctx.socket(zmq.REP)
server.bind('tcp://{0}:{1}'.format(host, port))

while True:
    req_bytes = server.recv()
    if req_bytes == b'time':
        rep = 'Current time: {0}'.format(
            datetime.datetime.utcnow().isoformat()).encode('utf-8')
        server.send(rep)

client

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
client = ctx.socket(zmq.REQ)
client.connect('tcp://{0}:{1}'.format(host, port))
client.send(b'time')
rep = client.recv().decode('utf-8')
print(rep)

入出力結果(Terminal, IPython)

server

$ ./sample2_server.py
^CTraceback (most recent call last):
  File "./sample2_server.py", line 15, in <module>
    req_bytes = server.recv()
  File "zmq/backend/cython/socket.pyx", line 693, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:7683)
  File "zmq/backend/cython/socket.pyx", line 727, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:7460)
  File "zmq/backend/cython/socket.pyx", line 145, in zmq.backend.cython.socket._recv_copy (zmq/backend/cython/socket.c:2344)
  File "zmq/backend/cython/checkrc.pxd", line 12, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:9621)
KeyboardInterrupt
$

client

$ ./sample2_client.py
Current time: 2017-01-20T02:44:59.519535
$

0 コメント:

コメントを投稿