没有合适的资源?快使用搜索试试~ 我知道了~
首页python实现的文件同步服务器实例
资源详情
资源评论
资源推荐

python实现的文件同步服务器实例实现的文件同步服务器实例
主要介绍了python实现的文件同步服务器,实例分析了文件同步服务器的原理及客户端、服务端的实现技巧,需要
的朋友可以参考下
本文实例讲述了python实现的文件同步服务器。分享给大家供大家参考。具体实现方法如下:
服务端使用asyncore, 收到文件后保存到本地。
客户端使用pyinotify监视目录的变化 ,把变动的文件发送到服务端。
重点:
1. 使用structs打包发送文件的信息,服务端收到后,根据文件信息来接收客户端传送过来的文件。
2. 客户端使用多线程,pyinotify监视到文件变化,放到队列中,由另外一个线程发送。
上代码:
服务端:服务端:
# receive file from client and store them into file use asyncore.#
#/usr/bin/python
#coding: utf-8
import asyncore
import socket
from socket import errno
import logging
import time
import sys
import struct
import os
import fcntl
import threading
from rrd_graph import MakeGraph
try:
import rrdtool
except (ImportError, ImportWarnning):
print "Hope this information can help you:"
print "Can not find pyinotify module in sys path, just run [apt-get install python-rrdtool] in ubuntu."
sys.exit(1)
class RequestHandler(asyncore.dispatcher):
def __init__(self, sock, map=None, chunk_size=1024):
self.logger = logging.getLogger('%s-%s' % (self.__class__.__name__, str(sock.getsockname())))
self.chunk_size = chunk_size
asyncore.dispatcher.__init__(self,sock,map)
self.data_to_write = list()
def readable(self):
#self.logger.debug("readable() called.")
return True
def writable(self):
response = (not self.connected) or len(self.data_to_write)
#self.logger.debug('writable() -> %s data length -> %s' % (response, len(self.data_to_write)))
return response
def handle_write(self):
data = self.data_to_write.pop()
#self.logger.debug("handle_write()->%s size: %s",data.rstrip(''),len(data))
sent = self.send(data[:self.chunk_size])
if sent < len(data):
remaining = data[sent:]
self.data_to_write.append(remaining)
def handle_read(self):
self.writen_size = 0
nagios_perfdata = '../perfdata'
head_packet_format = "!LL128s128sL"
head_packet_size = struct.calcsize(head_packet_format)
data = self.recv(head_packet_size)
if not data:
return
filepath_len, filename_len, filepath,filename, filesize = struct.unpack(head_packet_format,data)
filepath = os.path.join(nagios_perfdata, filepath[:filepath_len])
filename = filename[:filename_len]
self.logger.debug("update file: %s" % filepath + '/' + filename)
try:
if not os.path.exists(filepath):
os.makedirs(filepath)
except OSError:











安全验证
文档复制为VIP权益,开通VIP直接复制

评论0