2014年9月28日日曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング: 127.0.0.1という場所はない)、自分で考えてみよう(p.487)をpythonで考えてみる。

自分で考えてみよう(p.487)

コード(BBEdit, Emacs)

sample487.py

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

import os
import sys
import socket
import signal

listener_d = socket.socket()

def handleShutdown(sig, stack_frame):
    if listener_d:
        listener_d.close()
    print('さようなら!', file=sys.stderr)
    sys.exit(0)
    
signal.signal(signal.SIGINT, handleShutdown)
host = 'localhost'
port = 30000
address = (host, port)
listener_d.bind(address)
listener_d.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener_d.listen(10)

print('接続を待っています。')

while True:
    connect_d, address_info = listener_d.accept()
    if os.fork() == 0:
        listener_d.close()
        connect_d.send('Knock! Knock!\r\n'. encode('utf-8'))
        data = connect_d.recv(100)
        if data.decode('utf-8').startswith("Who's there?\r\n"):
            connect_d.send('Oscar\r\n'.encode('utf-8'))
            data = connect_d.recv(100)
            if data.decode('utf-8').startswith('Oscar who?'):
                connect_d.send(
                    'oscar silly question, your get a silly answer\r\n'.encode(
                        'utf-8'))
        connect_d.close()
        sys.exit(0)
    connect_d.close()

入出力結果(Terminal, IPython)

サーバー

$ ./sample487.py
接続を待っています。
  C-c C-cさようなら!
$

クライアント1

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Knock! Knock!
Who's there?
Oscar
Oscar who?
oscar silly question, your get a silly answer
Connection closed by foreign host.

Process telnet-127.0.0.1 30000 exited abnormally with code 1

クライアント2

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Knock! Knock!
Who's there?
Oscar
Oscar who?
oscar silly question, your get a silly answer
Connection closed by foreign host.

Process telnet-127.0.0.1 30000<1> exited abnormally with code 1

0 コメント:

コメントを投稿