2016年9月4日日曜日

開発環境

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

11-1

コード(Emacs)

server.py

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

import socket
import datetime

server_address = ('localhost', 6789)
max_size = 4096

print('Starting the server at {0}(socket)\n'
      'Waiting for a client to call.'.format(datetime.datetime.now()))

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_address)

while True:
    data, client = server.recvfrom(max_size)
    print('At {0} {1} said {2}.'.format(datetime.datetime.now(), client,
                                        data.decode('utf-8')))
    if data == 'time'.encode('utf-8'):
        server.sendto(datetime.datetime.now().isoformat().encode('utf-8'),
                      client)
        break
    else:
        server.sendto('?????'.encode('utf-8'), client)


server.close()

client.py

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

import socket
import datetime

server_address = ('localhost', 6789)
max_size = 4096

print('Starting the client at {0}(socket)'.format(datetime.datetime.now()))

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

for word in ['Hello', 'time']:
    client.sendto(word.encode('utf-8'), server_address)
    data, server = client.recvfrom(max_size, )
    print(data.decode('utf-8'))

client.close()

入出力結果(Terminal, IPython)

$ ./server.py > output.txt &
[1] 7595
$ ./client.py 
Starting the client at 2016-09-05 01:10:37.369557(socket)
?????
2016-09-05T01:10:37.376469
[1]+  Done                    ./server.py > output.txt
$ cat output.txt 
Starting the server at 2016-09-05 01:10:34.946923(socket)
Waiting for a client to call.
At 2016-09-05 01:10:37.374645 ('127.0.0.1', 61114) said Hello.
At 2016-09-05 01:10:37.376321 ('127.0.0.1', 61114) said time.
$

0 コメント:

コメントを投稿

Comments on Google+: