標籤:
這是《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"%cmd17 if cmd==‘ls‘:18 curdir=os.curdir19 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=e32 else:33 res="argument is illegal"34 elif cmd==‘date‘:35 res=datetime.date.today()36 else:37 res=‘command is illegal‘38 print res39 return str(res)40 while True:41 CliSock,addr=SerSock.accept()42 print "...connected from %s:%s"%addr43 while True:44 cmd=CliSock.recv(BUFSIZE)45 if not cmd:46 break47 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 continue20 CliSock.send(cmd)21 res=CliSock.recv(BUFSIZ)22 if not res:23 print "response from server error."24 print res25 26 CliSock.close()
執行結果:
Please input below command.*************************************date ls/ls dir os*************************************>date2015-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‘)>>>>>exitcommand is illegal>>>qcommand is illegal
Python簡單伺服器程式