socket的功能分割到不同函数

#!/usr/bin/env python3
#-*- encoding:utf8 -*-

import argparse,socket,time

aphorisms ={
    b'Beautiful is better than ?':b'Ugly.',
    b'Explicit is better than ?':b'Implicit.',
    b'Simple is better than?':b'Complex.'}

def get_answer(aphorism):
    time.sleep(0.0)
    return aphorisms.get(aphorism,b'Error:unknow aphorism')

def parse_command_line(description):
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('host',help='IP or Hostname')
    parser.add_argument('-p',type=int,help='TCP port number',metavar='port',default=1060)
    
    args=parser.parse_args()
    address =((args.host,args.p))

def create_srv_socket(address):
    listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    listener.bind(address)
    listener.listen(64)
    print('Listen at {}'.format(address))

def accept_connections_forever(listener):
    while True:
        sock,address = listener.accept()
        print('Acceptd connection from {}'.format(address))
        handle_conversation(sock,address)

def handle_conversation(sock,address):
    try:
        while True:
            handle_request(sock)
    except EOFError:
        print('Client {} error : {}'.format(address , e))
    finally:
        sock.close()


def handle_request(sock):
    aphorism = recv_until(sock , b'?')
    answer = get_answer(aphorism)
    sock.sendall(answer)

def recv_until(sock,suffix):
    message = sock.recv(4096)
    if not message:
        raise EOFError('socket closed')
    while not message.endswith(suffix):
        data = sock.recv(4096)
        if not data:
            raise IOError('Received {!r} then socket closed'.format(message))
        message += data
    return message

这段代码的好像是最后4个函数,这3个函数之间的层级调用过程。

posted @ 2017-06-30 01:13  alben-xue  阅读(269)  评论(0编辑  收藏  举报