代码来自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