设为首页 加入收藏

TOP

Python , 一个简单的单线程的C/S模型示例
2014-11-24 03:19:59 】 浏览:8855
Tags: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)


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 2.6.6安装MySQL-python模块 下一篇Struts2 convention-plugin 使用..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目