開発環境
- 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.1.を解いてみる。
Things to Do 11.1.
コード(Eacs, BBEdit)
server
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import datetime
import socket
server_address = ('localhost', 6789)
max_size = 4096
print('Starting the server at', datetime.datetime.now())
print('waiting for a client to call.')
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_address)
while True:
data, client = server.recvfrom(max_size)
print('received', data.decode('utf-8'))
if data == b'time':
now = datetime.datetime.now()
server.sendto(datetime.datetime.isoformat(now).encode('utf-8'), client)
else:
server.sendto(b'...', client)
server.close()
client
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import socket
server_address = ('localhost', 6789)
max_size = 4096
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s = ''
while True:
s = input()
if s == 'q':
break
client.sendto(s.encode('utf-8'), server_address)
print('send', s)
data, server = client.recvfrom(max_size)
print(data.decode('utf-8'))
client.close()
入出力結果(Terminal, IPython)
server
$ ./sample1_server.py Starting the server at 2015-05-07 12:52:54.901998 waiting for a client to call. received time received Hello received time C-c C-cTraceback (most recent call last): File "./sample1_server.py", line 16, in <module> data, client = server.recvfrom(max_size) KeyboardInterrupt $
client
$ ./sample1_client.py time send time 2015-05-07T12:53:01.192030 Hello send Hello ... time send time 2015-05-07T12:53:07.429335 q $
0 コメント:
コメントを投稿