2015年5月8日金曜日

開発環境

  • OS X Yosemite - Apple (OS)
  • Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
  • Python 3.4 (プログラミング言語)

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

Things to Do 11.2.

コード(Eacs, BBEdit)

server

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

import datetime
import zmq

server_address = ('127.0.0.1', 6789)

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

print('Starting the server at', datetime.datetime.now())
print('waiting for a client to call.')

while True:
    request_bytes = server.recv()
    request_str = request_bytes.decode('utf-8')
    print('received', request_str)
    if request_str == 'time':
        now = datetime.datetime.now()
        reply_str = datetime.datetime.isoformat(now)
        reply_bytes = reply_str.encode('utf-8')
        server.send(reply_bytes)
    else:
        server.send(b'...')

client

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

import zmq

server_address = ('127.0.0.1', 6789)

ctx = zmq.Context()
client = ctx.socket(zmq.REQ)
client.connect('tcp://{0}:{1}'.format(*server_address))

s = ''
while True:
    s = input()
    if s == 'q':
        break
    client.send(s.encode('utf-8'))
    print('send', s)
    reply_bytes = client.recv()
    reply_str = reply_bytes.decode('utf-8')
    print(reply_str)
    

入出力結果(Terminal, IPython)

server

$ ./sample2_server.py
Starting the server at 2015-05-08 12:27:26.110239
waiting for a client to call.
received time
received Hello
received time
  C-c C-cTraceback (most recent call last):
  File "./sample2_server.py", line 17, in <module>
    request_bytes = server.recv()
  File "zmq/backend/cython/socket.pyx", line 638, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:5785)
  File "zmq/backend/cython/socket.pyx", line 672, in zmq.backend.cython.socket.Socket.recv (zmq/backend/cython/socket.c:5585)
  File "zmq/backend/cython/socket.pyx", line 139, in zmq.backend.cython.socket._recv_copy (zmq/backend/cython/socket.c:1738)
  File "zmq/backend/cython/checkrc.pxd", line 11, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6035)
KeyboardInterrupt
$

client

$ ./sample2_client.py
time
send time
2015-05-08T12:27:31.308857
Hello
send Hello
...
time
send time
2015-05-08T12:27:33.840102
q
$

0 コメント:

コメントを投稿