Python简单服务器程序
这是《Python核心编程(中的文第二版)》的一个习题,题目要求服务器能识别以下命令:
ls 返回服务器程序当前目录
os 返回服务器操作系统的信息
date 得到服务器当前的时间
ls dir 返回目录dir的文件列表
服务器程序:
1 import time 2 import os 3 import datetime 4 5 HOST='' 6 PORT=21234 7 ADDR=(HOST,PORT) 8 BUFSIZE=8096 9 10 SerSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 11 SerSock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 12 SerSock.bind(ADDR) 13 SerSock.listen(5) 14 15 def process_cmd(cmd): 16 print "The command receive from client is:%s"%cmd 17 if cmd=='ls': 18 curdir=os.curdir 19 res=os.listdir(curdir) 20 elif cmd=='os': 21 res=os.uname() 22 elif cmd.startswith('ls'): 23 length=len(cmd.split()) 24 if length==1: 25 res="command is illegal" 26 elif length==2: 27 reqdir=cmd.split()[1] 28 try: 29 res=os.listdir(reqdir) 30 except OSError,e: 31 res=e 32 else: 33 res="argument is illegal" 34 elif cmd=='date': 35 res=datetime.date.today() 36 else: 37 res='command is illegal' 38 print res 39 return str(res) 40 while True: 41 CliSock,addr=SerSock.accept() 42 print "...connected from %s:%s"%addr 43 while True: 44 cmd=CliSock.recv(BUFSIZE) 45 if not cmd: 46 break 47 else: 48 res=process_cmd(cmd) 49 CliSock.send(res) 50 CliSock.close() 51 SerSock.close()
客户端程序:
1 #!/usr/bin/python 2 3 import socket 4 5 HOST='localhost' 6 PORT=21234 7 ADDR=(HOST,PORT) 8 BUFSIZ=8096 9 10 CliSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 11 CliSock.connect(ADDR) 12 print "Please input below command." 13 print "*************************************" 14 print "date ls/ls dir os" 15 print "*************************************" 16 while True: 17 cmd=raw_input(">") 18 if not cmd: 19 continue 20 CliSock.send(cmd) 21 res=CliSock.recv(BUFSIZ) 22 if not res: 23 print "response from server error." 24 print res 25 26 CliSock.close()
执行结果:
Please input below command. ************************************* date ls/ls dir os ************************************* >date 2015-06-09 >ls ['client_select.py', 'client.py', 'server_select.py', 'chat_server_v1.py', 'server.py', 'daytimeclient.py', 'chat_client_v1.py', 'chat_server_v2.py', 'tsTserv.py', 'tsTclnt.py'] >ls /home ['tmyyss'] >os ('Linux', 'ubuntu', '3.13.0-53-generic', '#89-Ubuntu SMP Wed May 20 10:34:28 UTC 2015', 'i686') > > > > >exit command is illegal > > >q command is illegal