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
时间: 2024-08-11 00:46:10

Python简单服务器程序的相关文章

nodejs的简单服务器程序

下面是参考<Jquery.Jquery UI 及Jquery Mobile>一书中的nodej服务器程序 var http = require('http'), url = require('url'), fs = require('fs'); http.createServer(function (req, res) { var reqData = { url: url.parse(req.url, true), method: req.method, headers: req.header

Socket编程回顾,一个最简单服务器程序

第一次接触服务器是快毕业的时候,是不是有点晚(# ̄ω ̄),这也导致工作方向一直没考虑网络编程这块,做了好多其他没啥“意思”的技术. 之前看到一篇博文提到程序猿80%都是庸才,10%是人才,10%是天才,深有感触.仔细想想自己是不是也是还在那80%里面挣扎?一个抱怨这抱怨那的trouble maker,写着烂的掉渣的代码,永远在别人身后不思进取,给剩下的20%的同事埋雷. 扯远了,重新回顾Socket,温习下Linux内核是怎么处理Socket的吧. 文件描述符,在网络编程中经常提及这个词,当时初

Python简单小程序练习

1.九九乘法表 #!/usr/bin/python for i in range(1,10): for j in range(i): j += 1 print ("%d * %d = %-2d " %(i, j, i*j)), print "" 2.水仙花 #!/usr/bin/python l = [] for a in range (100,1000): if (a/100%10)**3 + (a/10%10)**3 + (a%10)**3 == a: l.ap

PHP脚本语言写的简单服务器程序

<?php $username = $_POST["username"];/*客户端请求方式为POST,请求参数封装成nsdata类型放在HTTPBody中传给服务器,服务器用PHP脚本语言接收到请求参数,根据参数在服务器中查找数据返回给客户端*/ $password = $_POST["password"]; $type = $_POST["type"]; /*链接数据库 127.0.0.1是回送地址,网络软件测试以及本地机进程间通信*/

Python 简单购物程序

# Author:Eric Zhao# -*- coding:utf-8 -*-'''需求:启动程序后,让用户输入工资,然后打印商品列表允许用户根据商品编号购买商品用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额''' product_list = [ ('IPhone',5000), ('Bike', 500), ('Car', 50000), ('Hat', 50)]shopping_list = []salary = input('Plea

python简单小程序(99乘法表)

1. #99乘法表#第一种 for i in range(1,10): s='' for j in range (1,i+1): s+=str(j)+'*'+str(i)+'='+str(j*i)+'\t' print s #第二种 for i in range(1,10): s='' for j in range (1,i+1): s+=str(j)+'*'+str(i)+'='+'{0:2d}'.format(j*i)+'\t'  #{0:2d}解释:表示0 代表j*i,:2d 表示两个宽度

Python实现简单的http服务器程序

主要的需求是这样的,需要调用服务器端的程序获取GPU服务器的信息并且返回给前端显示出来,那么就需要完成一个服务器端的程序,获取服务器的数据之后将数据返回(以JSON格式). 效果如下图: 页面没有内容是因为服务程序还没有启动.下面完成服务器程序: #!/usr/bin/python from bottle import route,run,template import os from bottle import get,post,request import re gpu_info_dict

python脚本获取服务器外部连接IP并取出非本地服务器程序有关联的IP

#!/bin/env python #-*- coding:utf-8 -*- import os import sys from subprocess import Popen def get_foriegn_ip():         l = os.popen("netstat -ant|grep ESTABLISHED|awk '{print $5}'|awk -F: '{print $1}'|sort -r|uniq -c |awk '{print $2}'|grep -v 'and'|

简单的python协同过滤程序

1.使用Visual Studio 2012 2.下载 ModernUI.Templates 安装 给大家一个下载连接http://pan.baidu.com/s/1jGfxDlk 3.选择Modetrn UI WPF Appliction 4.打开MainWindow.xaml 考虑到平时菜单都是动态的从数据库读取出来的所以要由后台生成菜单 先把界面上的菜单删除掉 将整个<mui:ModernWindow.MenuLinkGroups>...</mui:ModernWindow.Men