Python , 一个简单的单线程的C/S模型示例

代码来自Foundations of Python network programming

python 版本2.7

launcelot.py

# !/usr/bin/env python

import socket,sys

PORT = 1060

qa = (('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 message

def 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 python

import launcelot

def 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 python

import sys,socket,launcelot,os

def 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 answer3

if __name__ == '__main__':
    port = 1060
    client('localhost',port)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e12adaefdfe90fdb9b8b86248963455d.html