python

来源:互联网 发布:lua for windows 5.2 编辑:程序博客网 时间:2024/04/28 23:47

                                                        python

 

# -*- coding: utf-8 -*-  
'''
多个客户端并发往服务端写东西,服务器负责接受并保存
如果日记达到10条(行),就往服务器写。
每隔10s,如果没收到客户端请求,也把内存数据保存在服务器文件中
'''
import SocketServer
import thread
import threading
from time import sleep,ctime
HOST = ''
PORT = 21567
ADDR = (HOST, PORT)



class MyRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print 'connected from:',self.client_address
        i = 0
        while True:
            try:
                #接收客户端传来的数据
                data=self.request.recv(1024)
                #往文件中写接收到的数据
                man_file.write(data)
                i = i + 1
                #每当日志达到10条(行),就往文件中写
                if i >= 10:
                    print 'flush data'
                    i = 0
                    #把内存的数据保存在文件,并清空
                    man_file.flush()
            except :
                print 'disconnect........... '
                break;
#每隔10秒中,就往服务器写日志
def delayTime():
    while True:
        print man_file
        sleep(10)
        man_file.flush()        
def main():
    tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler)
    print 'waiting for connection....'
    thread.start_new_thread(delayTime,())
    tcpServ.serve_forever()

if __name__ == '__main__':
     #在当前目录创建文件,并打开文件
    man_file=open('file.txt','a')
    try:
        main()
    except KeyboardInterrupt:
        print "server has been closed."
        #关闭文件
        man_file.close()

0 0