论坛首页 编程语言技术论坛

python中的SocketServer.StreamRequestHandler类中的读写说明

浏览 2246 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-09-12  
SocketServer.StreamRequestHandler中对客户端发过来的数据是用rfile属性来处理的,rfile是一个类file对象.有缓冲.可以按行分次读取;发往客户端的数据通过wfile属性来处理,wfile不缓冲数据,对客户端发送的数据需一次性写入.
如下代码:
#! /usr/bin/env python
#coding=utf-8
'''
单线程服务器程序
'''
from SocketServer import TCPServer as TCP, StreamRequestHandler as SRH

class MyTCPHandler(SRH):
    def handle(self):
        '''
        覆盖方法,对父类的方法重写
        '''
        self.firstline=self.rfile.readline().strip()
        
        #命令分发
        if(self.firstline=='login'):
            print 'if login'
            name=self.rfile.readline().strip()
            print name
            pwd=self.rfile.readline().strip()
            print name
            self.login(name,pwd)
        elif(self.firstline=='start_server'):
            pass
        elif(self.firstline=='stop_server'):
            pass
        elif(self.firstline=='open_firewall'):
            pass
        elif(self.firstline=='close_firewall'):
            pass
        elif(self.firstline=='read_firewall_ip_list'):
            pass
        elif(self.firstline=='write_firewall_ip_list'):
            pass
        elif(self.firstline=='read_server_ip_list'):
            pass
        elif(self.firstline=='write_server_ip_list'):
            pass
        elif(self.firstline=='remote_update'):
            pass
        elif(self.firstline=='local_synchronize'):
            pass
        else:
            print 'error'
            '''print self.rfile.readline()
            print self.rfile.readline()
            '''
            line=self.rfile.readline()
            while line!='':
                #self.wfile.write('%s' % line)
                line=self.rfile.readline()
                print line
[color=red]            self.wfile.write('ok'+'ok2'+'ok3')[/color]
            
    def login(self,name,pwd):
        print 'login'
        self.wfile.write(name+pwd+'ok')

if __name__ == "__main__":
    #本机,使用端口9999
    HOST, PORT = "localhost", 9999

    # 创建服务器并绑定到本机的9999端口
    server = TCP((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics