歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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)

Copyright © Linux教程網 All Rights Reserved