Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python , 一个简单的单线程的C/S模型示例

代码来自Foundations of python network programmingpython 版本2.7launcelot.py# !/usr/bin/env pythonimport socket,sysPORT = 1060qa = (("What is your name?","My name is Sir Lanucelot of Camelot."),
      ("what is your request?","To seek the Holy Grail."),
      ("what is your favourite color?","Bule."))qadict = dict(qa)def recv_until(sock,suffix):
    message = ""
    while not message.endswith(suffix):  #以特定符号断句,该过程是阻塞的,直到有该符号出现时,才会返回
        data = sock.recv(4096)  #the maxmum amount of data to be receieved at once
        if not data:
            raise EOFError("socket closed before we saw %r" %suffix)
        message += data
    return messagedef setup():    interface = "localhost"
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind((interface,PORT))
    sock.listen(128)  # the maximum queue number is 128
    print "Ready and listening at %r port %d" %(interface,PORT)
    return sock
                         
server_simple.py# !/usr/bin/env pythonimport launcelotdef handle_client(client_sock):
    try:
        while True:
            question = launcelot.recv_until(client_sock,"?")
            answer = launcelot.qadict[question]
            client_sock.sendall(answer)
    except EOFError:
        client_sock.close()def server_loop(listen_sock):
    while True:
        client_sock,sockname = listen_sock.accept()
        handle_client(client_sock)if __name__ == "__main__":
    listen_sock = launcelot.setup()
    server_loop(listen_sock)client.py# !/usr/bin/env pythonimport sys,socket,launcelot,osdef client(hostname,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((hostname,port))
    s.sendall(launcelot.qa[0][0])
    answer1 = launcelot.recv_until(s,".")
    s.sendall(launcelot.qa[1][0])
    answer2 = launcelot.recv_until(s,".")
    s.sendall(launcelot.qa[2][0])
    answer3 = launcelot.recv_until(s,".")
    s.close()    print answer1
    print answer2
    print answer3if __name__ == "__main__":
    port = 1060
    client("localhost",port)